Exemplo n.º 1
1
def authenticate():
    # Get client ID and secret from auth.ini
    config = get_config()
    # https://github.com/Imgur/imgurpython/blob/master/examples/auth.ini
    config.read('auth.ini')  # this is the file that holds user credentials
    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    client = ImgurClient(client_id, client_secret)

    # Authorization flow, pin example (see docs for other auth types)
    authorization_url = client.get_auth_url('pin')

    print (("Go to the following URL: {0}".format(authorization_url)))

    # Read in the pin, handle Python 2 or 3 here.
    pin = get_input("Enter pin code: ")

    # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
    config.set('credentials', 'refresh_token', credentials['refresh_token'])
    with open('auth.ini', 'w') as configfile:    # save
        config.write(configfile)

    print ("Authentication successful! Here are the details:")
    print (("   Access token:  {0}".format(credentials['access_token'])))
    print (("   Refresh token: {0}".format(credentials['refresh_token'])))

    return client
def main(argv):
	
	client_id = '.............'
	client_secret = '.............'
	pin = ""

	client = ImgurClient(client_id, client_secret)
	authorization_url = client.get_auth_url('pin')
	usage = "usage : make_credentials.py -p <pin number>"
	usage += "\nauthorization url : \n\t" + authorization_url
	
	try:
		opts, args = getopt.getopt(argv, "hp:", ["pin="])
		
		for opt, arg in opts:
			if opt == "-h":
				print(usage)
				sys.exit(2)
			elif opt in ("-p", "--pin"):
				pin = arg
		
		credentials = client.authorize(pin, 'pin')
		access_token = "access : " + credentials['access_token']
		refresh_token = "refres : " + credentials['refresh_token']
		print(access_token)
		print(refresh_token)
		keys = open("./token.txt", "w")
		keys.write(access_token + "\r\n")
		keys.write(refresh_token)
		keys.close()
	except getopt.GetoptError:
		print(usage)
Exemplo n.º 3
0
def authenticate():
    # Get client ID and secret from auth.ini
    config = get_config()
    # https://github.com/Imgur/imgurpython/blob/master/examples/auth.ini
    config.read('auth.ini')  # this is the file that holds user credentials
    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    client = ImgurClient(client_id, client_secret)

    # Authorization flow, pin example (see docs for other auth types)
    authorization_url = client.get_auth_url('pin')

    print(("Go to the following URL: {0}".format(authorization_url)))

    # Read in the pin, handle Python 2 or 3 here.
    pin = get_input("Enter pin code: ")

    # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])
    config.set('credentials', 'refresh_token', credentials['refresh_token'])
    with open('auth.ini', 'w') as configfile:  # save
        config.write(configfile)

    print("Authentication successful! Here are the details:")
    print(("   Access token:  {0}".format(credentials['access_token'])))
    print(("   Refresh token: {0}".format(credentials['refresh_token'])))

    return client
Exemplo n.º 4
0
class auth():
    def __init__(self):
        # Get client ID and secret from auth.ini
        # config = get_config()
        # config.read('auth.ini')
        self.client_id = os.environ.get('Client_ID')
        self.client_secret = os.environ.get('Client_Secret')
        self.client = ImgurClient(self.client_id, self.client_secret)

        # Authorization flow, pin example (see docs for other auth types)
        self.authorization_url = self.client.get_auth_url('pin')

        print("Go to the following URL: {0}".format(self.authorization_url))

        # Read in the pin, handle Python 2 or 3 here.
        pin = get_input("Enter pin code: ")

        # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
        credentials = self.client.authorize(pin, 'pin')
        self.client.set_user_auth(credentials['access_token'],
                                  credentials['refresh_token'])

        print("Authentication successful! Here are the details:")
        print("   Access token:  {0}".format(credentials['access_token']))
        print("   Refresh token: {0}".format(credentials['refresh_token']))
Exemplo n.º 5
0
def authenticate():
    """
    :rtype: client object
    """
    # result = os.getcwd()
    src_path = os.path.dirname(os.path.abspath(__file__))
    auth_path = "{0}/auth.ini".format(src_path)

    config = get_config()
    # config.read('auth.ini')
    config.read(auth_path)
    client_id = config.get('credentials','client_id')
    client_secret = config.get('credentials', 'client_secret')
    refresh_token = config.get('credentials', 'refresh_token')
    access_token = config.get('credentials', 'access_token')

    if not refresh_token:
        # print 'not refresh token'
        client = ImgurClient(client_id, client_secret)
        authorization_url = client.get_auth_url('pin')
        import webbrowser as wb
        print("First we need to have your authentication access...")
        print("Go to browser and open the following URL: {0}".format(authorization_url))
        wb.open_new_tab(authorization_url)

        pin = get_input("Enter the pin code: ")

        # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
        credentials = client.authorize(pin, 'pin')

        # Store the refresh_token
        new_refresh_token = credentials['refresh_token']
        config.set('credentials', 'refresh_token', value=new_refresh_token)
        refresh_token = new_refresh_token
        with open(auth_path, 'wb') as configfile:
            config.write(configfile)

    if refresh_token and not access_token:
        client.set_user_auth(access_token, refresh_token)
        # client = ImgurClient(client_id, client_secret, refresh_token)
        if not client.auth:
            print("Auth failed... Please try again")
            import sys
            sys.exit()
        else:
            print("Auth success! Getting accessing...")
            client.auth.refresh()
            new_access_token = client.auth.current_access_token
            print("New access token generated.")
            config.set('credentials', 'access_token', value=new_access_token)
            with open(auth_path, 'wb') as configfile:
                config.write(configfile)
            access_token = new_access_token
            print("Access information saved!")

    if refresh_token and access_token:
        # print 'refresh token and access token'
        client = ImgurClient(client_id, client_secret, access_token, refresh_token)

    return client
Exemplo n.º 6
0
def authenticate():
	# Get client ID and secret from auth.ini
	config = get_config()
	config.read('auth.ini')
	client_id = config.get('credentials', 'client_id')
	client_secret = config.get('credentials', 'client_secret')

	client = ImgurClient(client_id, client_secret)

	# Authorization flow, pin example (see docs for other auth types)
	authorization_url = client.get_auth_url('pin')

	print("Go to the following URL: {0}".format(authorization_url))

	# Read in the pin, handle Python 2 or 3 here.
	pin = get_input("Enter pin code: ")
        print type(pin)
	# ... redirect user to `authorization_url`, obtain pin (or code or token) ...
	credentials = client.authorize(pin, 'pin')
	client.set_user_auth(credentials['access_token'], credentials['refresh_token'])

	print("Authentication successful! Here are the details:")
	print("   Access token:  {0}".format(credentials['access_token']))
	print("   Refresh token: {0}".format(credentials['refresh_token']))

	return client
Exemplo n.º 7
0
def init_imgur_api(config_file):
    if isfile(config_file):
        with open(config_file, "rb") as fd:
            config = json.load(fd)
    else:
        config = {}
    if "client_id" not in config:
        config['client_id'] = raw_input("Please insert the client id: ")
    if "client_secret" not in config:
        config['client_secret'] = raw_input(
            "Please insert the client secret: ")
    if "refresh_token" not in config:
        imgurAPI = ImgurClient(config['client_id'], config['client_secret'])
        pin = raw_input("Please visit %s and paste the pin here: " %
                        imgurAPI.get_auth_url('pin'))
        credentials = imgurAPI.authorize(pin, 'pin')
        imgurAPI.set_user_auth(credentials['access_token'],
                               credentials['refresh_token'])
        config['refresh_token'] = credentials['refresh_token']
    else:
        imgurAPI = ImgurClient(config['client_id'],
                               config['client_secret'],
                               refresh_token=config['refresh_token'])
    # we always recreate the config as i am lazy and it would be bad to loose the refresh key
    with open(config_file, "wb") as fd:
        json.dump(config, fd)
    return imgurAPI
Exemplo n.º 8
0
 def imgur_auth_from_pin(self):
     # If there are no valid imgur auth tokens saved, authenticate with a pin to refresh/initialize them.
     imgur_client = ImgurClient(self.auth['client_id'],
                                self.auth['client_secret'])
     authorization_url = imgur_client.get_auth_url('pin')
     print(authorization_url)
     webbrowser.open(authorization_url)  # Launch web browser to get pin
     pin = input("Enter OAUTH pin: ")
     try:
         credentials = imgur_client.authorize(pin, 'pin')
         imgur_client.set_user_auth(credentials['access_token'],
                                    credentials['refresh_token'])
         self.auth['access_token'] = credentials['access_token']
         self.auth['refresh_token'] = credentials['refresh_token']
         with open('auth.json', 'w') as outfile:
             json.dump(self.auth, outfile, indent=4,
                       sort_keys=True)  # Cache keys for later use
         return imgur_client
     except Exception as e:
         log.warning("Could not connect to imgur. Retrying in 5s.")
         if self.FORCE_AUTH:
             time.sleep(5)  # This might not work with async
             self.imgur_auth_from_pin()
         else:
             raise e
Exemplo n.º 9
0
def swapCodeForTokens(response):
    # takes dict of response parameters as input, like {'error':'blah blah'} or {'code':'blah blah','state':'blah blah'}
    db = app.connect_db()
    c = db.cursor()
    state = json.loads(response['state'])
    user_identifier = state['id']
    redir = state['redir']
    if 'error' in response:
        c.execute(
            'UPDATE users SET imgur_json=NULL WHERE imgur_id=' +
            app.app.sqlesc, (user_identifier, ))
        db.commit()
        return {'success': False}
    # called at the server redirect when imgur returns the code
    client = ImgurClient(app.app.config['IMGUR_CLIENTID'],
                         app.app.config['IMGUR_SECRET'])
    credentials = client.authorize(response['code'], 'authorization_code')
    # print credentials
    if 'access_token' in credentials.keys(
    ) and 'refresh_token' in credentials.keys():
        db = app.connect_db()
        c = db.cursor()
        c.execute(
            'UPDATE users SET imgur_json=' + app.app.sqlesc +
            ' WHERE imgur_id=' + app.app.sqlesc,
            (json.dumps(credentials), user_identifier))
        db.commit()
        db.close()
        return {'success': True, 'redir': redir}
    else:
        c.execute(
            'UPDATE users SET imgur_json=NULL WHERE imgur_id=' +
            app.app.sqlesc, (user_identifier, ))
        db.commit()
        return {'success': False}
Exemplo n.º 10
0
def swapCodeForTokens(response):
	# takes dict of response parameters as input, like {'error':'blah blah'} or {'code':'blah blah','state':'blah blah'}
	db = app.connect_db()
	c=db.cursor()
	state = json.loads(response['state'])
	user_identifier = state['id']
	redir = state['redir']
	if 'error' in response:
		c.execute('UPDATE users SET imgur_json=NULL WHERE imgur_id='+app.app.sqlesc,(user_identifier,))
		db.commit()
		return {'success':False}
	# called at the server redirect when imgur returns the code
	client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET'])
	credentials = client.authorize(response['code'],'authorization_code')
	# print credentials
	if 'access_token' in credentials.keys() and 'refresh_token' in credentials.keys():
		db = app.connect_db()
		c = db.cursor()
		c.execute('UPDATE users SET imgur_json='+app.app.sqlesc+' WHERE imgur_id='+app.app.sqlesc,(json.dumps(credentials),user_identifier))
		db.commit()
		db.close()
		return {'success':True,'redir':redir}
	else:
		c.execute('UPDATE users SET imgur_json=NULL WHERE imgur_id='+app.app.sqlesc,(user_identifier,))
		db.commit()
		return {'success':False}
def authenticate():
    # iniファイル読み込み
    config: ConfigParser = configparser.ConfigParser()
    config.read(INI_FILE_NAME)
    client_id: str = config.get(INI_SECTION_TOKEN, INI_CLIENT_ID)
    client_secret: str = config.get(INI_SECTION_TOKEN, INI_CLIENT_SECRET)
    # クライアント生成
    if (config.has_option(INI_SECTION_TOKEN, INI_REFRESH_TOKEN)):
        # 既にトークン取得済みならそれを使用する
        refresh_toke: str = config.get(INI_SECTION_TOKEN, INI_REFRESH_TOKEN)
        access_toke: str = config.get(INI_SECTION_TOKEN, INI_ACCESS_TOKE)
        client = ImgurClient(client_id, client_secret, access_toke,
                             refresh_toke)
    else:
        client = ImgurClient(client_id, client_secret)
        # 認証
        authorization_url = client.get_auth_url('pin')
        webbrowser.open(authorization_url)
        print("Go to the following URL: {0}".format(authorization_url))
        pin = input("Enter pin code: ")
        credentials = client.authorize(pin, 'pin')
        client.set_user_auth(credentials['access_token'],
                             credentials['refresh_token'])
        refresh_toke = credentials['refresh_token']
        access_toke = credentials['access_token']
        # iniファイル書き出し
        config.set(INI_SECTION_TOKEN, 'refresh_toke', refresh_toke)
        config.set(INI_SECTION_TOKEN, 'access_toke', access_toke)
        with open(INI_FILE_NAME, 'w') as inifile:
            config.write(inifile)
    return client
def main(argv):

    client_id = '.............'
    client_secret = '.............'
    pin = ""

    client = ImgurClient(client_id, client_secret)
    authorization_url = client.get_auth_url('pin')
    usage = "usage : make_credentials.py -p <pin number>"
    usage += "\nauthorization url : \n\t" + authorization_url

    try:
        opts, args = getopt.getopt(argv, "hp:", ["pin="])

        for opt, arg in opts:
            if opt == "-h":
                print(usage)
                sys.exit(2)
            elif opt in ("-p", "--pin"):
                pin = arg

        credentials = client.authorize(pin, 'pin')
        access_token = "access : " + credentials['access_token']
        refresh_token = "refres : " + credentials['refresh_token']
        print(access_token)
        print(refresh_token)
        keys = open("./token.txt", "w")
        keys.write(access_token + "\r\n")
        keys.write(refresh_token)
        keys.close()
    except getopt.GetoptError:
        print(usage)
Exemplo n.º 13
0
def authenticate(authFile='auth.ini'):

    # get all credentials and login data
    config = ConfigParser.ConfigParser()
    config.read(authFile)
    credentials = {k: v for k, v in config.items('credentials')}
    loginData = {k: v for k, v in config.items('imgurLogin')}
    client = ImgurClient(credentials['client_id'],
                         credentials['client_secret'])

    authorization_url = client.get_auth_url('pin')

    # use selenium to login to user's account and get the pin
    # there's no better way to do this due to imgur's api limitations
    browser = webdriver.PhantomJS()
    browser.get("https://imgur.com/signin")
    username = browser.find_element_by_xpath("//input[@name='username']")
    username.send_keys(loginData['username'])
    password = browser.find_element_by_xpath("//input[@name='password']")
    password.send_keys(loginData['password'])
    password.send_keys(Keys.ENTER)
    browser.get(authorization_url)
    pin = browser.find_element_by_xpath("//input[@name='pin']").get_attribute(
        'value')

    browser.close()
    browser.quit()

    response = client.authorize(pin, 'pin')
    client.set_user_auth(response['access_token'], response['refresh_token'])

    return client
Exemplo n.º 14
0
def authenticate():
	# Get client ID and secret from auth.ini
	config = configparser.ConfigParser()
	config.read('auth.ini')
	client_id = config.get('credentials', 'client_id')
	client_secret = config.get('credentials', 'client_secret')

	client = ImgurClient(client_id, client_secret)

	# Authorization flow, pin example (see docs for other auth types)
	authorization_url = client.get_auth_url('pin')

	print("Go to the following URL: {0}".format(authorization_url))

	# Read in the pin, handle Python 2 or 3 here.
	pin = get_input("Enter pin code: ")

	# ... redirect user to `authorization_url`, obtain pin (or code or token) ...
	credentials = client.authorize(pin, 'pin')
	client.set_user_auth(credentials['access_token'], credentials['refresh_token'])

	print("Authentication successful! Here are the details:")
	print("   Access token:  {0}".format(credentials['access_token']))
	print("   Refresh token: {0}".format(credentials['refresh_token']))

	return client
Exemplo n.º 15
0
def get_img():
    client_id = 'b9ae77105014a61'
    client_secret = '720fc83b0d748eb6131f987949280e15bf3a6e66'
    client = ImgurClient(client_id, client_secret)
    authorization_url = client.get_auth_url('pin')
    print("Go to the following URL: {0}".format(authorization_url))
    if os.path.isfile('pin.txt'):
        with open('pin.txt', 'r') as f:
            pin = f.read()
    else:
        pin = input("Enter pin code: ")
        with open('pin.txt', 'w') as f:
            f.write(pin)
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])
    # Example request
    album_id = 'ARm1Dtq'
    config = {
        'album': album_id,
        'name': 'test-name!',
        'title': 'test-title',
        'description': 'test-description'
    }
    print(client.get_album('ARm1Dtq'))
    client.upload_from_path('D:/python/linebot/linebot/in.jpg',
                            config=config,
                            anon=False)
    images = client.get_album_images(album_id)
    url = images[len(images) - 1].link
    return url
Exemplo n.º 16
0
class SimpleImgurClient:
    def __init__(self, username=''):
        self.load_config()
        self.username = username
        self.client = ImgurClient(self.client_id, self.client_secret)
        self.client.set_user_auth(self.access_token, self.refresh_token)
        self.authorization_url = self.client.get_auth_url('pin')
    
    def load_config(self):
        config = get_config()
        config.read('auth.ini')
        self.client_id = config.get('credentials', 'client_id')
        self.client_secret = config.get('credentials', 'client_secret')
        self.access_token = config.get('credentials', 'access_token')
        self.refresh_token = config.get('credentials', 'refresh_token')
    
    def authenticate(self):
        print("Get your access PIN here: %s" % (self.authorization_url,))
        pin = get_input("Please enter your PIN: ")
        self.authorize(pin)
    
    def authorize(self, pin):
        credentials = self.client.authorize(pin, 'pin')
        self.client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
        self.access_token = credentials['access_token']
        self.refresh_token = credentials['refresh_token']
        self.save()
    
    def save(self):
        with open('auth.ini', 'w') as sessionfile:
            sessionfile.write("[credentials]\n")
            sessionfile.write("client_id={0}\n".format(self.client_id))
            sessionfile.write("client_secret={0}\n".format(self.client_secret))
            sessionfile.write("access_token={0}\n".format(self.access_token))
            sessionfile.write("refresh_token={0}\n".format(self.refresh_token))

    def whoami(self):
        '''Request account information from IMGUR server'''
        acc = self.client.get_account('me')
        # print("Account ID : %s" % (acc.id))
        # print("Account URL: %s" % (acc.url))
        # print("Account bio: %s" % (acc.bio))
        return acc
        
    def backup_myfavs(self, max_page_count=1):
        imgs = []
        with codecs.open('myfav.htm', 'w', 'utf-8') as myfav:
            for page in range(max_page_count):
                print("Fetching page #%s" % (page,))
                myfav.write("<h1>Page #%s</h1>" % (page))
                myfav.write("<table>")
                myfav.write("<tr><td>Title</td><td>Description</td><td>Datetime</td><td>Link</td></tr>")
                favs = self.client.get_account_favorites('me', page)
                for img in favs:
                    imgs.append(img)
                    myfav.write("<tr><td>%s</td><td>%s</td><td>%s</td><td><a href='%s'>%s</a><br/></td></tr>\n" % (img.title, img.description, datetime.datetime.fromtimestamp(img.datetime), img.link, img.link))
                    # myfav.write('<a href="%s">%s</a><br/>\n' % (img.link, img.link))
                myfav.write("</table>")
        return imgs
Exemplo n.º 17
0
def authenticate():
    #client_id = '854786241b5ff16'
    #client_secret = '90c6a5b0068fa60c3b6b047fffec2388fe6cd6c8'

    config = configparser.ConfigParser()
    config.read('auth.ini')

    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    imgur_username = config.get('credentials', 'imgur_username')
    imgur_password = config.get('credentials', 'imgur_password')

    client = ImgurClient(client_id, client_secret)

    authorization_url = client.get_auth_url('pin')

    print("Go to the following URL: {0}".format(authorization_url))

    browser = webdriver.Chrome()
    browser.get(authorization_url)

    username = browser.find_element_by_xpath('//*[@id="username"]')
    password = browser.find_element_by_xpath('//*[@id="password"]')
    username.clear()
    username.send_keys(imgur_username)
    password.send_keys(imgur_password)

    browser.find_element_by_name("allow").click()

    timeout = 2
    try:
        element_present = EC.presence_of_element_located((By.ID, 'pin'))
        WebDriverWait(browser, timeout).until(element_present)
        pin_element = browser.find_element_by_id('pin')
        pin = pin_element.get_attribute("value")
    except TimeoutException:
        print("Timed out waiting for page to load")

    print("Your pin is : " + pin)

    # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])

    print("Authentication successful! Here are the details:")
    print("   Access token:  {0}".format(credentials['access_token']))
    print("   Refresh token: {0}".format(credentials['refresh_token']))

    browser.close()

    return client
Exemplo n.º 18
0
def get_imgur_client(client_id, client_secret):
  try:
    client = ImgurClient(client_id, client_secret)
    authorization_url = client.get_auth_url('pin')
    imgur_pin = raw_input('Please visit %s and enter the pin given to you there: ' % authorization_url)
    credentials = client.authorize(imgur_pin, 'pin')
    client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
  except ImgurClientError as e:
    print('Imgur error #%d: "%s"' % (e.status_code, e.error_message))
    print('Proceeding without enabling Imgur integration.')
    client = False

  return client
Exemplo n.º 19
0
    def handle(self, *args, **options):
        client = ImgurClient(CONSUMER_ID, CONSUMER_SECRET)

        url = client.get_auth_url('pin')
        print "Url:", url
        print "Please visit this website and press the 'Allow' button, then paste the PIN code you receive from Imgur."
        pin = raw_input().strip()

        # This will fail if the user didn't visit the above URL and hit 'Allow'
        credentials = client.authorize(pin, 'pin')

        print "IMGUR_ACCESS_TOKEN = '%s'" % credentials['access_token']
        print "IMGUR_ACCESS_TOKEN_REFRESH = '%s'" % credentials['refresh_token']
Exemplo n.º 20
0
    def handle(self, *args, **options):
        client = ImgurClient(CONSUMER_ID, CONSUMER_SECRET)

        url = client.get_auth_url('pin')
        print "Url:", url
        print "Please visit this website and press the 'Allow' button, then paste the PIN code you receive from Imgur."
        pin = raw_input().strip()

        # This will fail if the user didn't visit the above URL and hit 'Allow'
        credentials = client.authorize(pin, 'pin')

        print "IMGUR_ACCESS_TOKEN = '%s'" % credentials['access_token']
        print "IMGUR_ACCESS_TOKEN_REFRESH = '%s'" % credentials['refresh_token']
Exemplo n.º 21
0
def authenticate():
    client_id = '<REPLACE WITH YOUR IMGUR CLIENT ID>'
    client_secret = '<REPLACE WITH YOUR IMGUR CLIENT SECRET>'

    client = ImgurClient(client_id, client_secret)
    authorization_url = client.get_auth_url('pin')

    print('Go to the following URL: {}'.format(authorization_url))
    pin = get_input('Enter pin code: ')

    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])
    return client
Exemplo n.º 22
0
def imgur_login():
    """Logins to Imgur"""

    config = get_config(True)

    if not config:
        click.echo("Cannot upload - could not find IMGUR_API_ID or "
                   "IMGUR_API_SECRET environment variables or config file")
        return

    client = ImgurClient(config["id"], config["secret"])

    authorization_url = client.get_auth_url('pin')

    click.echo("Please Go To {}".format(authorization_url))

    login_pin = click.prompt('Please enter pin from the imgur login')

    credentials = client.authorize(login_pin, 'pin')

    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])

    configvalues = ['access_token', 'refresh_token']

    for value in configvalues:
        with open(os.path.expanduser(
                '~/.config/imgur_uploader/uploader.cfg')) as cf:
            lines = cf.readlines()
            ln = len(value)
            for ind, line in enumerate(lines):
                if value == line[:ln]:
                    lines[ind:ind + 1] = []
                    break
            with open(
                    os.path.expanduser(
                        '~/.config/imgur_uploader/uploader.cfg'), "w") as out:
                out.writelines(lines)

    with open(os.path.expanduser('~/.config/imgur_uploader/uploader.cfg'),
              "a") as cf:
        cf.write("access_token=")
        cf.write(credentials['access_token'])
        cf.write("\nrefresh_token=")
        cf.write(credentials['refresh_token'])

    return {
        "access_token": credentials['access_token'],
        "refresh_token": credentials['refresh_token']
    }
Exemplo n.º 23
0
def authenticate():
    client = ImgurClient(client_id, client_secret)

    authorization_url = client.get_auth_url('pin')

    pin = getPin(authorization_url)
    print("Get pin {0}".format(pin))

    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])

    print("Authentication finished.")

    return client
Exemplo n.º 24
0
def get_imgur_client(client_id, client_secret):
    try:
        client = ImgurClient(client_id, client_secret)
        authorization_url = client.get_auth_url('pin')
        imgur_pin = raw_input(
            'Please visit %s and enter the pin given to you there: ' %
            authorization_url)
        credentials = client.authorize(imgur_pin, 'pin')
        client.set_user_auth(credentials['access_token'],
                             credentials['refresh_token'])
    except ImgurClientError as e:
        print('Imgur error #%d: "%s"' % (e.status_code, e.error_message))
        print('Proceeding without enabling Imgur integration.')
        client = False

    return client
Exemplo n.º 25
0
    def authenticate(self):
        """Connect and authenticate user with Imgur"""
        if self.client is not None:
            return

        # lasts for one month, access to user's account
        access_token = None
        # request new access token without more authorization process, does not expire
        refresh_token = None
        try:
            auth_file = open(CREDENTIALS_FILE, "r")
            lines = auth_file.read().split("\n")
            auth_file.close()
            if (len(lines) < 2):
                raise Exception("Imgur: Missing tokens in file")
            access_token = lines[0]
            refresh_token = lines[1]
            if access_token is None or refresh_token is None:
                raise Exception("Imgur: Empty tokens in file")
            client = ImgurClient(self.app_id, self.app_secret, access_token,
                                 refresh_token)
            print("Imgur: Authenticated with saved credentials")
        except:
            print(
                "Imgur: Could not read authorization credentials, opening browser to authenticate..."
            )
            imgur_client = ImgurClient(self.app_id, self.app_secret)
            auth_url = imgur_client.get_auth_url('pin')
            webbrowser.open_new_tab(auth_url)
            pin = input("Enter PIN: ")
            try:
                credentials = imgur_client.authorize(pin, 'pin')
                client = ImgurClient(self.app_id, self.app_secret,
                                     credentials['access_token'],
                                     credentials['refresh_token'])
            except:
                print("Error authenticating PIN:", sys.exc_info()[1])
                sys.exit()

            auth_file = open(CREDENTIALS_FILE, "w")
            auth_file.write(credentials['access_token'] + "\n")
            auth_file.write(credentials['refresh_token'])
            auth_file.close()
            print("Imgur: Successfully authenticated and saved to file!")

        self.client = client
Exemplo n.º 26
0
    def __init__(self, name, clientId, clientSecret):
        self.name = name
        self.clientId = clientId
        self.clientSecret = clientSecret

        self.accountUsername = None
        self.accountId = None
        self.refreshToken = None

        client = ImgurClient(self.clientId, self.clientSecret)
        authorization_url = client.get_auth_url('pin')
        print(authorization_url)
        pin = input("Enter the pin given by the link:")
        credentials = client.authorize(pin, 'pin')
        self.refreshToken = credentials['refresh_token']
        self.accountUsername = credentials['account_username']
        self.accountId = credentials['account_id']
Exemplo n.º 27
0
def get_imgur_tokens(client_id, client_secret):

    client = ImgurClient(client_id, client_secret)
    authorization_url = client.get_auth_url('pin')
    print('Go to the following URL: {0}'.format(authorization_url))
    pin = input('Enter pin code: ')

    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(
        credentials['access_token'], credentials['refresh_token'])

    print('Authentication successful! Check details in the .log file')
    logging.info('Authentication successful! Here are the details:')
    logging.info(' Access token:  {0}'.format(credentials['access_token']))
    logging.info(' Refresh token: {0}'.format(credentials['refresh_token']))

    return credentials['access_token'], credentials['refresh_token']
Exemplo n.º 28
0
 def _authenticate(self, settings):
     client_id = settings.get('credentials', 'client_id')
     client_secret = settings.get('credentials', 'client_secret')
     client = ImgurClient(client_id, client_secret)
     authorization_url = client.get_auth_url('pin')
     sys.stdout.write('\nGo to the following URL:\n  >> {0}\n\n'.format(authorization_url))
     sys.stdout.flush()
     pin = get_input('Enter pin code: ')
     credentials = client.authorize(pin, 'pin')
     client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
     settings.set('credentials', 'refresh_token', credentials['refresh_token'])
     sys.stdout.write('\nAuthentication successful! Here are the details:\nAccess token: {0}\n'
                      'Refresh token: {1}\n** Configuration Updated **\n\n'.format(
                         credentials['access_token'], credentials['refresh_token']))
     sys.stdout.flush()
     self.save_settings()
     return client
Exemplo n.º 29
0
def getauthorize():

    client = ImgurClient(client_id, client_secret)

    authorization_url = client.get_auth_url('pin')

    print("Go to the following URL: {0}".format(authorization_url))

    pin = input("Enter pin code: ")

    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(
        credentials['access_token'], credentials['refresh_token'])

    print("Authentication successful! Here are the details:")
    print("   Access token:  {0}".format(credentials['access_token']))
    print("   Refresh token: {0}".format(credentials['refresh_token']))
    return client
Exemplo n.º 30
0
def logins():
    config = configparser.ConfigParser()
    config.read('auth.ini')

    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    imgur_username = config.get('credentials', 'imgur_username')
    imgur_password = config.get('credentials', 'imgur_password')

    client = ImgurClient(client_id, client_secret)

    authorized_url = client.get_auth_url('pin')

    driver = webdriver.PhantomJS()
    driver.get(authorized_url)

    username = driver.find_element_by_xpath('//*[@id="username"]')
    password = driver.find_element_by_xpath('//*[@id="password"]')
    username.clear()
    username.send_keys(imgur_username)
    password.send_keys(imgur_password)

    driver.find_element_by_name("allow").click()

    timeout = 5
    try:
        element_present = EC.presence_of_element_located((By.ID, 'pin'))
        WebDriverWait(driver, timeout)
        pin_element = driver.find_element_by_id('pin')
        pin = pin_element.get_attribute("value")

    except TimeoutException:
        print("timeout")
    driver.close()

    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])
    print("success")
    # print(client)

    return client
Exemplo n.º 31
0
def authenticate():
    config = configparser.ConfigParser()

    my_ini = find_file_path('auth.ini')
    config.read(my_ini)

    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    imgur_username = config.get('credentials', 'imgur_username')
    imgur_password = config.get('credentials', 'imgur_password')

    client = ImgurClient(client_id, client_secret)

    authorization_url = client.get_auth_url('pin')
    my_drive = find_file_path("chromedriver.exe")
    driver = webdriver.Chrome(executable_path=my_drive)
    driver.get(authorization_url)

    username = driver.find_element_by_xpath('//*[@id="username"]')
    password = driver.find_element_by_xpath('//*[@id="password"]')
    username.clear()
    username.send_keys(imgur_username)
    password.send_keys(imgur_password)

    driver.find_element_by_name("allow").click()

    timeout = 5
    try:
        element_present = EC.presence_of_element_located((By.ID, 'pin'))
        WebDriverWait(driver, timeout).until(element_present)
        pin_element = driver.find_element_by_id('pin')
        pin = pin_element.get_attribute("value")
    except TimeoutException:
	       print("Timed out waiting for page to load")
    driver.close()

    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
    print("Authentication successful!")


    return client
Exemplo n.º 32
0
def authenticate_user():
    try:
        pin = config.get('credentials', 'PIN')
        client_id = config.get('credentials', 'CLIENT_ID')
        client_secret = config.get('credentials', 'CLIENT_SECRET')
        access_token = config.get('credentials', 'ACCESS_TOKEN')
        refresh_token = config.get('credentials', 'REFRESH_TOKEN')
        album = config.get('album', 'ALBUM_ID') or None
        client = ImgurClient(client_id, client_secret)

        if refresh_token == '':
            try:
                credentials = client.authorize(pin, 'pin')
                access = credentials['access_token']
                refresh = credentials['refresh_token']
                raise Warning(
                    f'{colors.blue}ACCESS_TOKEN={colors.default}{access} {colors.blue}REFRESH_TOKEN={colors.default}{refresh}'
                )
            except ImgurClientError as error:
                print(
                    f'{colors.red}ERROR:{colors.default} Invalid pin {colors.orange}{pin}{colors.default}'
                )
                authorization_url = client.get_auth_url('pin')
                raise Warning(
                    f'Please visit {colors.blue}{authorization_url}{colors.default} to generate a new pin.'
                )
        else:
            client.set_user_auth(access_token, refresh_token)
            return {"client": client, "album": album}

    except configparser.NoOptionError:
        raise ValueError(
            f'{colors.red}ERROR:{colors.blue} CLIENT_ID{colors.default}/{colors.blue}CLIENT_SECRET{colors.default} not found.'
        )

    except configparser.NoSectionError:
        raise ValueError(
            f'{colors.red}ERROR:{colors.orange} auth.ini{colors.default} not found.'
        )

    except TypeError as error:
        raise ValueError(error)
Exemplo n.º 33
0
def get_authorization():
    #get authorization from user
    client = ImgurClient("a5d6a74712d69cc", "a7b83fe3bfdb6c21135c1f41f1d10de37638c5b3")

    webbrowser.open(client.get_auth_url("pin"))

    print("Before using imgurbox you need to authorize it to access you imgur account.")
    print("A page has been opened in your browser. Click \"Allow\" and then copy the PIN number.")
    pin = input("Enter authorization PIN here: ")

    credentials = client.authorize(pin, "pin")
    client.set_user_auth(credentials["access_token"], credentials["refresh_token"])

    #save credentials for next time
    log_msg("Received user authorization. Tokens: {0}:{1}".format(credentials["access_token"], credentials["refresh_token"]))

    with open("credentials.txt", "w") as f:
        f.write(credentials["access_token"] + "\n" + credentials["refresh_token"] + "\n")

    return client
class ImgurBot:
    def __init__(self):
        self.client = None

        self.authorized = False
        if (req_info.needToAddInfo(useImgur=True)):
            print(
                "Need to update required_info.py with correct credentials before running, see README for more info"
            )
        super().__init__()

    def authenticate(self):
        self.client = ImgurClient(req_info.client_id_imgur,
                                  req_info.client_secret_imgur)
        authorization_url = self.client.get_auth_url('pin')
        print("Go to the following URL: {0}".format(authorization_url))
        # Read in the pin, handle Python 2 or 3 here.
        pin = get_input("Enter pin code: ")
        # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
        credentials = self.client.authorize(pin, 'pin')
        self.client.set_user_auth(credentials['access_token'],
                                  credentials['refresh_token'])
        print("Authentication successful! Here are the details:")
        print("   Access token:  {0}".format(credentials['access_token']))
        print("   Refresh token: {0}".format(credentials['refresh_token']))
        self.authorized = True

    def getalbums(self):
        albums = self.client.get_account_albums(req_info.imgur_account, page=0)
        print("Done")
        print(albums)

    def upload_to_album(self, albumId, title, description, image_url):
        config = {
            'album': albumId,
            'name': title,
            'title': title,
            'description': description
        }
        self.client.upload_from_url(image_url, config=config, anon=False)
        pass
def authenticate():
    conf = config.read_file(CONFIG_FILE)
    # Get client ID and secret from auth.ini

    client = ImgurClient(conf.imgur.client_id, conf.imgur.client_secret)

    # Authorization flow, pin example (see docs for other auth types)
    authorization_url = client.get_auth_url('pin')

    print("Go to the following URL: {0}".format(authorization_url))

    # Read in the pin
    pin = input("Enter pin code: ")

    # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'], credentials['refresh_token'])

    print("Authentication successful! Here are the details:")
    print("   Access token:  {0}".format(credentials['access_token']))
    print("   Refresh token: {0}".format(credentials['refresh_token']))
Exemplo n.º 36
0
def swapCodeForTokens(response):
    # takes dict of response parameters as input, like {'error':'blah blah'} or {'code':'blah blah','state':'blah blah'}
    db = app.connect_db()
    c = db.cursor()
    state = json.loads(response["state"])
    user_identifier = state["id"]
    redir = state["redir"]
    if "error" in response:
        c.execute(
            "UPDATE users SET imgur_json=NULL WHERE imgur_id=" +
            app.app.sqlesc,
            (user_identifier, ),
        )
        db.commit()
        return {"success": False}
    # called at the server redirect when imgur returns the code
    client = ImgurClient(app.app.config["IMGUR_CLIENTID"],
                         app.app.config["IMGUR_SECRET"])
    credentials = client.authorize(response["code"], "authorization_code")
    # print credentials
    if "access_token" in credentials.keys(
    ) and "refresh_token" in credentials.keys():
        db = app.connect_db()
        c = db.cursor()
        c.execute(
            "UPDATE users SET imgur_json=" + app.app.sqlesc +
            " WHERE imgur_id=" + app.app.sqlesc,
            (json.dumps(credentials), user_identifier),
        )
        db.commit()
        db.close()
        return {"success": True, "redir": redir}
    else:
        c.execute(
            "UPDATE users SET imgur_json=NULL WHERE imgur_id=" +
            app.app.sqlesc,
            (user_identifier, ),
        )
        db.commit()
        return {"success": False}
Exemplo n.º 37
0
def authenticate():
    config = configparser.ConfigParser()
    config.read('auth.ini')

    client_id = config.get('credentials', 'client_id')
    client_secret = config.get('credentials', 'client_secret')

    imgur_username = config.get('credentials', 'client_user')
    imgur_password = config.get('credentials', 'client_password')

    client = ImgurClient(client_id, client_secret)
    authoritzation_url = client.get_auth_url('pin')

    # This opens the authoritzation url and get the pin
    driver = webdriver.Firefox(
        executable_path=os.path.join(os.getcwd(), '../geckodriver'))
    driver.get(authoritzation_url)
    username = driver.find_element_by_xpath('//*[@id="username"]')
    password = driver.find_element_by_xpath('//*[@id="password"]')
    username.send_keys(imgur_username)
    password.send_keys(imgur_password)
    driver.find_element_by_name("allow").click()

    timeout = 5
    try:
        element_present = ec.presence_of_element_located((By.ID, 'pin'))
        WebDriverWait(driver, timeout).until(element_present)
        pin_element = driver.find_element_by_id('pin')
        pin = pin_element.get_attribute("value")
    except TimeoutException:
        print("Timed out waiting for page to load")
    driver.close()

    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])
    print("Authentication successfull")

    return client
Exemplo n.º 38
0
def imgur_authenticate_pin():

    # https://api.imgur.com/oauth2/addclient
    client_id = ""
    client_secret = ""

    client = ImgurClient(client_id, client_secret)

    authorization_url = client.get_auth_url("pin")

    print("Go to the following URL: {0}".format(authorization_url))
    try:
        pin = raw_input("Enter Pin\n")
    except:
        pin = input("Enter Pin\n")

    credentials = client.authorize(pin, "pin")
    client.set_user_auth(credentials["access_token"],
                         credentials["refresh_token"])
    print "\n\n"

    return client
Exemplo n.º 39
0
def authenticate():
    conf = config.read_file(CONFIG_FILE)
    # Get client ID and secret from auth.ini

    client = ImgurClient(conf.imgur.client_id, conf.imgur.client_secret)

    # Authorization flow, pin example (see docs for other auth types)
    authorization_url = client.get_auth_url('pin')

    print("Go to the following URL: {0}".format(authorization_url))

    # Read in the pin
    pin = input("Enter pin code: ")

    # ... redirect user to `authorization_url`, obtain pin (or code or token) ...
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(credentials['access_token'],
                         credentials['refresh_token'])

    print("Authentication successful! Here are the details:")
    print("   Access token:  {0}".format(credentials['access_token']))
    print("   Refresh token: {0}".format(credentials['refresh_token']))
Exemplo n.º 40
0
def authenticate(settings):
    client_id = settings.get('credentials', 'client_id')
    client_secret = settings.get('credentials', 'client_secret')

    client = ImgurClient(client_id, client_secret)
    authorization_url = client.get_auth_url('pin')

    print(("\nGo to the following URL: {0}".format(authorization_url)))
    pin = get_input("Enter pin code: ")

    # ... redirect user to `authorization_url`,
    # obtain pin (or code or token) ...
    credentials = client.authorize(pin, 'pin')
    client.set_user_auth(
        credentials['access_token'], credentials['refresh_token'])

    settings.set('credentials', 'refresh_token', credentials['refresh_token'])

    print(("Authentication successful! Here are the details:"))
    print(("   Access token:  {0}".format(credentials['access_token'])))
    print(("   Refresh token: {0}".format(credentials['refresh_token'])))

    return client
Exemplo n.º 41
0
def imgur():
    fields = (
        'client_id',
        'client_secret',
        'access_token',
        'refresh_token',
    )
    context = OrderedDict()
    for field in fields:
        context[field] = request.form.get(field, '')

    creds = Credentials.for_imgur()

    if request.method == 'POST':
        client_id = context['client_id']
        client_secret = context['client_secret']
        creds.data = context
        if client_id and client_secret:
            client = ImgurClient(client_id, client_secret)
            authorization_url = client.get_auth_url('code')
            return redirect(authorization_url)
    elif 'code' in request.args:
        data = creds.data
        client_id = data['client_id']
        client_secret = data['client_secret']
        client = ImgurClient(client_id, client_secret)
        code = request.args['code']

        credentials = client.authorize(code, 'authorization_code')
        client.set_user_auth(
            credentials['access_token'], credentials['refresh_token'])
        data.update(credentials)
        context.update(data)
        creds.data = data

    return render_template(
        'imgur.html', context=context, **context)
Exemplo n.º 42
0
class Login(QtWidgets.QDialog):
    def __init__(self):
        QtWidgets.QDialog.__init__(self)
        self.client = None

        self.setWindowTitle('imgshare')
        self.resize(250, 50)
        self.center()
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

        self.message = QtWidgets.QLabel('please enter pin')
        self.message.setObjectName('message')
        self.message.setAlignment(QtCore.Qt.AlignCenter)

        self.textpin = QtWidgets.QLineEdit(self)
        self.buttonLogin = QtWidgets.QPushButton('login', self)

        self.buttonPin = QtWidgets.QPushButton('get pin', self)

        self.buttonLogin.clicked.connect(self.handle_pin)
        self.buttonPin.clicked.connect(self.authenticate)

        layout = QtWidgets.QGridLayout(self)
        layout.addWidget(self.buttonPin, 0, 0)
        layout.addWidget(self.textpin, 1, 1)
        layout.addWidget(self.message, 0, 1)
        layout.addWidget(self.buttonLogin, 1, 0)

        self.setStyleSheet("""
            QDialog {
                background-color: rgb(50,50,50);
            }
            QLineEdit {
                border-color: solid black;
                selection-color: green;
            }
            QLabel {
                color: white;
            }
            QLabel#message {
                color: #85BF25;
                font: bold 14px;
            }
            QPushButton {
                background-color: rgb(50,50,50);
                border-color: solid black;
                border-width: 2px;
                color: rgb(255,255,255);
                font: bold 14px;
            }
            """)
        self.init_client()

    def init_client(self):
        try:
            client_id = '912116b2944a624'
            client_secret = 'c4fc62a0b62338f9e25f9062147e2d0ca44f428e'
            self.client = ImgurClient(client_id, client_secret)
        except ImgurClientError as e:
            stat_code = str(e.status_code)
            err_msg = str(e.error_message)
            QtWidgets.QMessageBox.warning(self, stat_code, "Error " + "\"" + err_msg + "\"" +
                                          "\n\nIt seems imgur is having some issues! Please restart imshare")
            self.appExit()

    def appExit(self):
        sys.exit()

    def authenticate(self):
        # authenticate imgur user login
        authorization_url = self.client.get_auth_url('pin')
        open_new_tab(authorization_url)

    def handle_pin(self):
        try:
            credentials = self.client.authorize(str(self.textpin.text()), 'pin')
            self.accept()
            self.client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
            return self.client

        except ImgurClientError as e:
            QtWidgets.QMessageBox.warning(self, str(e.status_code), str(e.error_message))

    def center(self):
        qr = self.frameGeometry()
        cp = QtWidgets.QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())
Exemplo n.º 43
0
class ImgurUp(object):

    def __init__(self):
        self.work_left = True
        builder = gtk.Builder()
        builder.add_from_file('%s/data/main_window.ui' % basepath)
        builder.connect_signals(self)
        self.windowstate = 1
        self.user_auth = 0
        self.imagepath = builder.get_object('imagepath')
        self.imagetitle = builder.get_object('imagetitle')
        self.imagecaption = builder.get_object('imagecaption')
        self.image = builder.get_object('imagepreview')
        self.filefilter = builder.get_object('filefilter1')
        self.filefilter.set_name("Image Files")
        self.filefilter.add_pixbuf_formats()
        self.menu1 = builder.get_object('menu1')
        self.window = builder.get_object('window1')
        self.text_info = builder.get_object('label39')
        self.statusicon = gtk.StatusIcon()
        self.statusicon.set_from_file('%s/data/imgurup.svg' % basepath)
        self.statusicon.connect("popup-menu", self.right_click_event)
        self.statusicon.connect("activate", self.icon_clicked)
        self.statusicon.set_tooltip("Imgur Uploader")
        self.window.connect("drag_data_received", self.on_file_dragged)
        self.window.drag_dest_set(gtk.DEST_DEFAULT_MOTION | gtk.DEST_DEFAULT_DROP,
                                 dnd_list, gtk.gdk.ACTION_COPY)
        self.window.show_all()
        if int(config['workmode']) == 0:
            self.albums = builder.get_object('albumbutton')
            self.albums.set_sensitive(False)
            self.user = builder.get_object('authorbutton')
            self.user.set_sensitive(False)
        else:
            self.il = ImgurClient(config['imgurkey'], config['imgursecret'])
            if config['usertoken'] and config['usersecret']:
                self.il = ImgurClient(config['imgurkey'], config['imgursecret'], config['usertoken'], config['usersecret'])
                self.user_auth = 1
            else:
                self.user_info()

    def exit(self, widget=None):
        if quit_msg("<b>Are you sure to quit?</b>") == True:
            gtk.main_quit()
        else:
            return False

    def on_window1_destroy(self, widget, data=None):
        self.window.hide_on_delete()
        self.windowstate = 0
        return True

    def select_image(self, widget, data=None):
        filedlg = gtk.FileChooserDialog("Select image file...", None,
                      gtk.FILE_CHOOSER_ACTION_OPEN,
                      (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL,
                      gtk.STOCK_OPEN, gtk.RESPONSE_OK))
        filedlg.add_filter(self.filefilter)
        response = filedlg.run()
        if response == gtk.RESPONSE_OK:
            self.imagepath.set_text(filedlg.get_filename())
            imgname = os.path.basename(filedlg.get_filename())
            pixbuf = gtk.gdk.pixbuf_new_from_file(filedlg.get_filename())
            self.image.set_from_pixbuf(pixbuf.scale_simple(300, 200, gtk.gdk.INTERP_NEAREST))
            self.imagetitle.set_text(imgname.split('.')[0].title())
        else:
            filedlg.destroy()
        filedlg.destroy()

    def upload_image(self, widget, data=None):
        if self.check_fields() == True:
            self.text_info.set_markup("<b><i>Uploading...</i></b>")
            config = {"title": self.imagetitle.get_text(),
            "description": self.imagecaption.get_text()}
            info = self.il.upload_from_path(self.imagepath.get_text(),
                                 config)
            if show_info(basepath, info) == True:
                f = open('%s/recent.txt' % basepath, 'a')
                f.write(info+"\n\r")
                f.close()
                menuItem = gtk.MenuItem(simplejson.loads(info)['images']['image']['title'])
                menuItem.connect('activate', lambda term: show_info(basepath, info))
                self.menu1.append(menuItem)
                self.menu1.show_all()
            self.text_info.set_text("")

    def check_fields(self):
        if not self.imagepath.get_text():
            return False
        elif not self.imagecaption.get_text():
            self.imagecaption.set_text("None")
        else:
            return True

    def clear_fields(self, widget, data=None):
        self.imagetitle.set_text("")
        self.imagepath.set_text("")
        self.imagecaption.set_text("")
        self.image.set_from_file("%s/data/imgurup-logo.png" % basepath)

    def take_screenshot(self, widget, data=None):
        if config['screenshotpath'] != "":
            path = config['screenshotpath']
        else:
            path = os.getenv("HOME")
        if self.windowstate == 1:
            self.window.hide()
            self.windowstate = 0
            shot = self.fullscreen_shot(path)
            uploadfile = path+"/"+shot
            self.window.show_all()
            self.windowstate = 1
        else:
            shot = self.fullscreen_shot(path)
            self.window.show_all()
            self.windowstate = 1
        self.imagepath.set_text(path+"/"+shot)
        pixbuf = gtk.gdk.pixbuf_new_from_file(path+"/"+shot)
        self.image.set_from_pixbuf(pixbuf.scale_simple(300, 200, gtk.gdk.INTERP_NEAREST))
        self.imagetitle.set_text(shot.split('.')[0].title())
        if bool(config['captionremove']) == False:
            self.imagecaption.set_text("Desktop Screenshot with ImgurUp")


    def fullscreen_shot(self, path = os.getenv('HOME')):
        from string import Template
        imgformat = "png"
        width = gtk.gdk.screen_width()
        height = gtk.gdk.screen_height()
        s = Template(config['screenshotname'])
        shotname = s.safe_substitute(date = time.strftime("%Y%m%d%H%M%S", time.localtime()),
                     time = time.strftime("H%M%S", time.localtime()),
                     count = config['count'])
        time.sleep(float(config['waitscreen']))
        screenshot = gtk.gdk.Pixbuf.get_from_drawable(
                    gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, width, height),
                    gtk.gdk.get_default_root_window(),
                    gtk.gdk.colormap_get_system(),
                    0, 0, 0, 0, width, height)
        screenshot.save(path+"/"+shotname+"."+imgformat, imgformat)
        config['count'] = int(config['count']) + 1
        config.write()
        return shotname+"."+imgformat

    def show_albums(self, widget, data=None):
        AlbumsDialog(basepath, self.il)

    def about_click(self, widget, data=None):
        AboutDialog(basepath)

    def on_file_dragged(self, widget, context, x, y, select, target, timestamp):
        imagepath = "/" + select.data.strip('\r\n\x00').strip("file://")
        if mimetypes.guess_type(imagepath)[0].startswith('image') == True:
            self.imagepath.set_text(imagepath)
            imagename = os.path.basename(imagepath)
            pixbuf = gtk.gdk.pixbuf_new_from_file(imagepath)
            self.image.set_from_pixbuf(pixbuf.scale_simple(300, 200, gtk.gdk.INTERP_NEAREST))
            self.imagetitle.set_text(imagename.split('.')[0].title())
        else:
            pass

    def user_info(self, sender=None, data=None):
        builder = gtk.Builder()
        builder.add_from_file('%s/data/main_window.ui' % basepath)
        userinfo = builder.get_object('userdialog')
        authimage = builder.get_object('image1')
        authtext = builder.get_object('label15')
        username = builder.get_object('label19')
        prof = builder.get_object('label18')
        privacy = builder.get_object('label21')
        credits = builder.get_object('label23')
        authbut = builder.get_object('button3')
        if self.user_auth == 1:
            info = self.il.get_account('me')
            authimage.set_from_stock(gtk.STOCK_OK, gtk.ICON_SIZE_SMALL_TOOLBAR)
            authtext.set_markup('<span foreground="green">Authenticated</span>')
            username.set_text(info.url)
            prof.set_text(str(info.pro_expiration))
            #privacy.set_text(info['account']['default_album_privacy'])
            info = self.il.get_credits()
            credits.set_markup('<b>%s</b> credits left' % info['UserRemaining'])
            authbut.set_sensitive(False)
        else:
            authbut.connect("clicked", self.authenticate)

        userinfo.add_buttons(gtk.STOCK_CLOSE, gtk.RESPONSE_CLOSE)
        userinfo.run()
        userinfo.destroy()

    def authenticate(self, widget=None, data=None):
        authdialog = gtk.Dialog("Authenticate", None, gtk.DIALOG_MODAL|gtk.DIALOG_DESTROY_WITH_PARENT,
                                      (gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT,
                                       gtk.STOCK_OK, gtk.RESPONSE_ACCEPT))
        link = gtk.LinkButton(self.il.get_auth_url('pin'), "Click here...")
        label = gtk.Label("Visit the following Link and paste the PIN code")
        entry = gtk.Entry()
        authdialog.vbox.pack_start(label)
        authdialog.vbox.pack_start(link)
        authdialog.vbox.pack_start(entry)
        authdialog.show_all()

        response = authdialog.run()
        print response
        if response == gtk.RESPONSE_ACCEPT:
            try:
                credentials = self.il.authorize(entry.get_text(), 'pin')
                self.user_auth = 1
                self.il.set_user_auth(credentials['access_token'], credentials['refresh_token'])
                config['usertoken'] = credentials['access_token']
                config['usersecret'] = credentials['refresh_token']
                config.write()
            except:
                error_msg("The PIN was not correct")
                authdialog.destroy()
        authdialog.destroy()

    def open_preferences(self, sender, data=None):
        PrefsDialog(basepath, config)

    def icon_clicked(self, sender, data=None):
        if(self.windowstate == 0):
            self.window.show_all()
            self.windowstate = 1
        else:
            self.window.hide_on_delete()
            self.windowstate = 0
            return True

    def right_click_event(self, icon, button, time):
        menu = gtk.Menu()

        about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
        logview = gtk.ImageMenuItem()
        logview.set_image(gtk.image_new_from_icon_name('emblem-photos', gtk.ICON_SIZE_MENU))
        logview.set_label("Account Albums")
        logview.connect("activate", self.show_albums)
        quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
        about.connect("activate", self.about_click)
        quit.connect("activate", self.exit)
        apimenu = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
        apimenu.set_label("Preferences")
        apimenu.connect("activate", self.open_preferences)
        shotmenu = gtk.ImageMenuItem(gtk.STOCK_FULLSCREEN)
        shotmenu.set_label("Take Screenshot")
        shotmenu.connect("activate", self.take_screenshot)

        menu.append(about)
        menu.append(logview)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(shotmenu)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(apimenu)
        menu.append(gtk.SeparatorMenuItem())
        menu.append(quit)
        menu.show_all()

        menu.popup(None, None, gtk.status_icon_position_menu,
                   button, time, self.statusicon)