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 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 get_imgur_client(read_new_client=False, read_new_token=False) -> ImgurClient: access_keys_dict = get_access_keys_dict() client_id, client_secret = extract_client_keys(access_keys_dict, read_new_client) try: client = ImgurClient(client_id=client_id, client_secret=client_secret) except ImgurClientError as e: print(e) print('Invalid credentials supplied. Let\'s try again :)') return get_imgur_client(read_new_client=True, read_new_token=read_new_token) access_token, refresh_token = extract_tokens(access_keys_dict, client, read_new_token) print("Authentication successful! Here are the details:") print(" Access token: {0}".format(access_token)) print(" Refresh token: {0}".format(refresh_token)) client.set_user_auth(access_token, refresh_token) write_access_keys({ CLIENT_ID: client_id, CLIENT_SECRET: client_secret, ACCESS_TOKEN: access_token, REFRESH_TOKEN: refresh_token }) return client
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
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
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 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
def uploadToImgur(userid,url): db = app.connect_db() c = db.cursor() c.execute('SELECT map_url,name,farmname,date,imgur_json FROM playerinfo WHERE url='+app.app.sqlesc,(url,)) result = c.fetchone() if result[4] != None: previous_upload_properties = json.loads(result[4]) if time.time() < previous_upload_properties['upload_time']+(2*3600): return {'error':'too_soon','link':previous_upload_properties['imgur_url']} map_url = result[0] titlestring = u"{} Farm, {} by {}".format(result[2],result[3],result[1]) descriptionstring = u"Stardew Valley game progress, full summary at http://upload.farm/{}".format(url) # try: c.execute('SELECT imgur_json FROM users WHERE id='+app.app.sqlesc,(userid,)) r = json.loads(c.fetchone()[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token,refresh_token) # file = url_for('home',filename=map_url,_external=True) # print 'uploaded to',file # client.upload_from_url(file,config={'title':'uploaded from','description':'upload.farm'},anon=False) if app.app.config['IMGUR_DIRECT_UPLOAD'] == True: result = client.upload_from_path(map_url,config={'title':titlestring,'description':descriptionstring},anon=False) else: map_url = u"http://upload.farm/{}".format(map_url) result = client.upload_from_url(map_url,config={'title':titlestring,'description':descriptionstring},anon=False) print(result) imgur_json = json.dumps({'imgur_url':'http://imgur.com/'+result['id'],'upload_time':time.time()}) c.execute('UPDATE playerinfo SET imgur_json='+app.app.sqlesc+' WHERE url='+app.app.sqlesc,(imgur_json,url)) db.commit() try: return {'success':None,'link':result['link']} except: return {'error':'upload_issue','link':None}
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']))
def UploadPhoto(image, title, name, description): access_token, refresh_token, client_id, client_secret = Config.getImgurKeys( ) client = ImgurClient(client_id, client_secret) client.set_user_auth(access_token, refresh_token) config = {'name': title, 'title': name, 'description': description} retVal = None tryCount = 0 while tryCount < 4: try: retVal = client.upload_from_path(image, config=config, anon=False) break except: tryCount += 1 if retVal == None: retVal = client.upload_from_path(image, config=config, anon=False) return retVal #def main(): # #x = CreateAlbum('Album 101','Album 101 desciption') # id = [] # id.append( UploadPhoto('outputImages\\narendramodi_6.jpg')['id']) # id.append( UploadPhoto('outputImages\\narendramodi_5.jpg')['id']) # #id.append( UploadPhoto(['outputImages\\narendramodi_4.jpg'])['id']) # x = CreateAlbumAndUploadImages('album1-1-1','some description',id) # pass #if __name__ == '__main__': # main()
def get_clients(): CLIENT_ID = 'f6b55c4c63de8411' CLIENT_SECRET = '5c2e28b4d73fd5599bf4c394d0165d45dfdae0a52' ACCESS_TOKEN = 'bad0ee1b8356d91d961e1e89690e11f16f1156083' REFRESH_TOKEN = '9f5dfc928b1fe5b9a51ee46f4db21b41bae886614' ##auth_url = client.get_auth_url('pin') ## ##credentials = client.authorize('7fd0bb2377', 'pin') ##client.set_user_auth(credentials['access_token'], credentials['refresh_token']) ##print('access token: {}\nrefresh_token: {}'.format(credentials['access_token'], credentials['refresh_token'])) imgur_client = ImgurClient(CLIENT_ID, CLIENT_SECRET, ACCESS_TOKEN, REFRESH_TOKEN) imgur_client.set_user_auth(ACCESS_TOKEN, REFRESH_TOKEN) reddit = praw.Reddit(client_id='anlOIy2SKazBqZA', client_secret='bajOvPWgxHIBrOMOk6GRmBI8bG4o', password='******', user_agent='abdulinker', username='******') subreddit = reddit.subreddit('feedtesting') logger.debug('Currently working from {}'.format(os.getcwd())) return (reddit, subreddit, imgur_client)
def main(s_argv): argv = s_argv argv["user"] = "******" argv["album"] = "youjung_ioi"#"chungha_ioi" argv["dump"] = "dump.txt" argv["save_path"] = "./save_list.txt" argv["complete_path"] = "./complete.txt" name_list = [] img_oriUrl_list = [] board_url = "" count = 1 name_flag = False #img_upload(access, refresh) _access_token, _refresh_token = get_access_token() print(_access_token) print(_refresh_token) client = ImgurClient(client_id, client_secret) client.set_user_auth(_access_token, _refresh_token) client.mashape_key = x_mash_key #print(client.credits["ClientLimit"]) #print("usr : %s, album : %s" % (argv["user"], argv["album"])) # album_id = get_album_id(client, argv["user"], argv["album"]) x_mash_info = get_x_mash_limit(client) remain = int(x_mash_info[0])
def checkApiAccess(userid): # something that checks whether we have api keys and whether they work; # if not, return False db = app.connect_db() c = db.cursor() c.execute('SELECT imgur_json FROM users WHERE id=' + app.app.sqlesc, (userid, )) r = c.fetchone() if len(r) > 0: try: r = json.loads(r[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] except TypeError: return False else: return False client = ImgurClient(app.app.config['IMGUR_CLIENTID'], app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token, refresh_token) try: client.get_account('me').url credits = client.credits # print(credits) if credits['ClientRemaining'] > 10 and credits['UserRemaining'] > 10: return True else: return None except ImgurClientError: return False
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
class imgur: imgur_client_id = '48a4853a9c844df' imgur_client_secret = 'ebe25d36f196cff544aca408e8d7b02283290c50' refresh_token = "1750e9d83514f1b4f9c6260ba7974ade9c0ab58a" client = None def imgur_init(self): self.client = ImgurClient(self.imgur_client_id, self.imgur_client_secret) url = "https://api.imgur.com/oauth2/token" payload = { 'refresh_token': self.refresh_token, 'client_id': self.imgur_client_id, 'client_secret': self.imgur_client_secret, 'grant_type': 'refresh_token' } headers = {} files = [] response = requests.request("POST", url, headers=headers, data=payload, files=files) a = json.loads(response.text) self.client.set_user_auth(a["access_token"], a["refresh_token"]) def upload_fking_image(self): self.client.upload_from_path(r"pil_text_font2.png", anon=False)
def authenticateImgur(): client_id = 'b50f2d93f8d16b0' client_secret = 'bfc148a6e9b61923f8b6d5db7db6c6d940a48f29' client = ImgurClient(client_id, client_secret) client.set_user_auth('6f5d0cf446bf216b9617e7a29bf637c212812fcc', '8b4641ffdf4c0cb66984466624f326461cf49600') #https://api.imgur.com/oauth2/authorize?client_id=8fbf5c5728003fa&response_type=pin #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 = input("Enter pin code: ") # ... redirect user to `authorization_url`, obtain pin (or code or token) ... #authorization_url = client.get_auth_url('pin') #credentials = client.authorize(pin, 'pin') #client.set_user_auth(credentials['access_token'], credentials['refresh_token']) #client.set_user_auth('6f5d0cf446bf216b9617e7a29bf637c212812fcc', '8b4641ffdf4c0cb66984466624f326461cf49600') #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 checkApiAccess(userid): # something that checks whether we have api keys and whether they work; # if not, return False db = app.connect_db() c = db.cursor() c.execute('SELECT imgur_json FROM users WHERE id='+app.app.sqlesc,(userid,)) r = c.fetchone() if len(r) > 0: try: r = json.loads(r[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] except TypeError: return False else: return False client = ImgurClient(app.app.config['IMGUR_CLIENTID'],app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token,refresh_token) try: client.get_account('me').url credits = client.credits # print(credits) if credits['ClientRemaining'] > 10 and credits['UserRemaining'] > 10: return True else: return None except ImgurClientError: return False
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
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
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
def uploadToImgur(userid, url): db = app.connect_db() c = db.cursor() c.execute( 'SELECT map_url,name,farmname,date,imgur_json FROM playerinfo WHERE url=' + app.app.sqlesc, (url, )) result = c.fetchone() if result[4] != None: previous_upload_properties = json.loads(result[4]) if time.time() < previous_upload_properties['upload_time'] + (2 * 3600): return { 'error': 'too_soon', 'link': previous_upload_properties['imgur_url'] } map_url = result[0] titlestring = u"{} Farm, {} by {}".format(result[2], result[3], result[1]) descriptionstring = u"Stardew Valley game progress, full summary at http://upload.farm/{}".format( url) # try: c.execute('SELECT imgur_json FROM users WHERE id=' + app.app.sqlesc, (userid, )) r = json.loads(c.fetchone()[0]) access_token = r['access_token'] refresh_token = r['refresh_token'] client = ImgurClient(app.app.config['IMGUR_CLIENTID'], app.app.config['IMGUR_SECRET']) client.set_user_auth(access_token, refresh_token) # file = url_for('home',filename=map_url,_external=True) # print 'uploaded to',file # client.upload_from_url(file,config={'title':'uploaded from','description':'upload.farm'},anon=False) if app.app.config['IMGUR_DIRECT_UPLOAD'] == True: result = client.upload_from_path(map_url, config={ 'title': titlestring, 'description': descriptionstring }, anon=False) else: map_url = u"http://upload.farm/{}".format(map_url) result = client.upload_from_url(map_url, config={ 'title': titlestring, 'description': descriptionstring }, anon=False) print(result) imgur_json = json.dumps({ 'imgur_url': 'http://imgur.com/' + result['id'], 'upload_time': time.time() }) c.execute( 'UPDATE playerinfo SET imgur_json=' + app.app.sqlesc + ' WHERE url=' + app.app.sqlesc, (imgur_json, url)) db.commit() try: return {'success': None, 'link': result['link']} except: return {'error': 'upload_issue', 'link': None}
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
def authed(): config = get_config() config.read('auth.ini') client_id = config.get('credentials', 'client_id') access_token = config.get('credentials', 'access_token') client_secret = config.get('credentials', 'client_secret') client = ImgurClient(client_id, client_secret) client.set_user_auth(credentials['access_token'], credentials['refresh_token'])
def set_old_tokens(credentials_dict): client = ImgurClient(credentials_dict['client_id'], credentials_dict['client_secret'], credentials_dict['refresh_token']) client.set_user_auth(credentials_dict['access_token'], credentials_dict['refresh_token']) return client
def UploadPhotoInAlbum(id, album): access_token, refresh_token, client_id, client_secret = Config.getImgurKeys( ) client = ImgurClient(client_id, client_secret) client.set_user_auth(access_token, refresh_token) config = { 'name': 'htht!', 'title': 'hththt!', 'description': 'this is a test' } return client.album_add_images(album, [id])
def upload_images(album_title, paths): client = ImgurClient(client_id, client_secret) client.set_user_auth(imgur_access_token, imgur_refresh_token) fields = {'title': album_title} album = client.create_album(fields) for i, img in enumerate(paths): config = {'album': album['id'], 'name': str(i), 'title': str(i)} image = client.upload_from_path(img, config=config, anon=False) remove(img) return album
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
def upload_images(album_title, paths): client = ImgurClient(client_id, client_secret) client.set_user_auth(imgur_access_token, imgur_refresh_token) fields = {"title": album_title} album = client.create_album(fields) for i, img in enumerate(paths): config = {"album": album["id"], "name": str(i), "title": str(i)} image = client.upload_from_path(img, config=config, anon=False) remove(img) return album
def img_upload(_access_token, _refresh_token): client = ImgurClient(client_id, client_secret) client.set_user_auth(_access_token, _refresh_token) client.mashape_key = x_mash_key conf = {"album" : "JtebE", "description": "Hello World", "title" : "Hi"} res = client.upload_from_path("./image_1_2.gif", config = conf, anon = False) print(res) print(res["link"])
def CreateAlbumAndUploadImages(albumName, albumDescription, images): access_token, refresh_token, client_id, client_secret = Config.getImgurKeys( ) client = ImgurClient(client_id, client_secret) client.set_user_auth(access_token, refresh_token) fields = {} fields['title'] = albumName fields['description'] = albumDescription fields['privacy'] = 'public' x = client.create_album(fields) y = client.album_add_images(x['id'], images) return x
def imgur_upload(image, name): client = ImgurClient(imgur_client_id, imgur_client_secret) authorization_url = client.get_auth_url('pin') client.set_user_auth(imgur_access_token, imgur_refresh_token) config = { 'album': 'IbzLr', 'name': name, 'title': name, 'description': name } image = client.upload_from_path(image, config=config, anon=False) return image['link']
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
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
def upload(self, url): imagecloud = ImageCloud().get_by_id('1') logging.info('Image cloud: '+str(imagecloud)) try: client = ImgurClient(imagecloud.client_id, imagecloud.client_secret) client.set_user_auth(imagecloud.access_token, imagecloud.refresh_token) conf = {"album" : "KHz1y"} resp = client.upload_from_url(url, config=conf, anon=False) logging.info('Resp imgur: '+str(resp)) return resp['link'] except Exception as e: logging.info("Erro imgur: "+str(e)) raise ErrorUploadImage
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'] }
def uploadImages(self): ''' uploads the print sheets to imgur and saves the urls. ''' global config df.loadConfig() client = ImgurClient(df.client_id, df.client_secret) client.set_user_auth(config["imgurAccessToken"], config["imgurRefreshToken"]) imIds = [] for i in self.printSheetPaths: temp = client.upload_from_path(i, anon=False) imIds.append(temp['id']) self.printSheetUrls.append(temp['link'])
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
def authenticate(): settings = ConfigParser.ConfigParser() settings.read(["config"]) client_id = settings.get('imgur','client_id') client_secret = settings.get('imgur','client_secret') access_token = settings.get('imgur','access_token') refresh_token = settings.get('imgur','refresh_token') client = ImgurClient(client_id, client_secret) client.set_user_auth(access_token, refresh_token) print("Authentication successful!") return client
def authenticate(): config = json.loads(os.environ.get("imgur_credentials").replace("'", "\"")) print("Auth: ", config) client_id = config.get('client_id', None) client_secret = config.get('client_secret', None) imgur_username = config.get('imgur_username', None) imgur_password = config.get('imgur_password', None) access_token = config.get('access_token', None) refresh_token = config.get('refresh_token', None) client = ImgurClient(client_id, client_secret) client.set_user_auth(access_token, refresh_token) return client
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
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
def imgur_auth(): """Run the initial Imgur auth flow""" client_id = current_app.config['IMGUR_CLIENT_ID'] client_secret = current_app.config['IMGUR_CLIENT_SECRET'] client = ImgurClient(client_id, client_secret) authorization_url = client.get_auth_url('token') print 'Please visit:', authorization_url access_token = prompt('Access Token') refresh_token = prompt('Refresh Token') client.set_user_auth(access_token, refresh_token) u = User.query.get(1) if u is None: u = User() u.uid = 1 u.access_token = access_token u.refresh_token = refresh_token db.session.add(u) db.session.commit()
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
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']))
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
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)
def create(self, parameters): assert self.share_type == Bi.Image if self.progress_callback: self.progress_callback(-1) client = ImgurClient(self.CLIENT_ID, self.CLIENT_SECRET) if self.login: client.set_user_auth(self.config['login'][self.login]['access_token'], self.config['login'][self.login]['refresh_token']) image = upload_contents(client, self.content, { 'name': parameters['Filename'], 'title': parameters['Title'], 'description': parameters['Description'] }, self.login is None) ro_url = image['link'][:image['link'].rindex('.')] rw_url = 'https://imgur.com/delete/' + image['deletehash'] if self.progress_callback: self.progress_callback(100) return {'View': ro_url, 'Delete': rw_url}
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())
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)
from imgurpython.helpers.error import ImgurClientError from imgurpython.helpers.error import ImgurClientRateLimitError from discord.ext import commands from .utils import checks import json import random from urllib.parse import urlparse from os.path import splitext from enum import Enum configFile = open('config.json') configDict = json.load(configFile) imgurClient = ImgurClient(configDict['imgur_client_id'], configDict['imgur_client_secret']) imgurClient.set_user_auth(configDict['imgur_access_token'], configDict['imgur_refresh_token']) class linkType(Enum): album = 1 imgurlink = 2 other = 3 def makeAlbumFromAlbum(title, albumlink): albumName = title.lower() for album in imgurClient.get_account_albums('me'): if albumName == album.title.lower(): print('aaaaa') # await self.bot.say(albumName + " is already an album") break
class ImgurBot: """ A class that implements a bot for interfacing with Imgur. """ version = "0.2a" # From https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words. # Space not included since it's safe in these use cases. Other characters are probably safe too, but YMMV. # TODO: Figure out if any other characters can be pruned from this list for enhanced user-friendliness. restricted_filesystem_chars = "/\\?*%:|\"<>." log_levels = {"Debug": 5, "Information": 4, "Warning": 3, "Error": 2, "Fatal": 1} def __init__(self, name="ImgurBot", print_at_log_level="Warning", testing_mode=False): """Initialize the ImgurBot. :type name: str This constructor has a testing_mode option which sets the name and then exits. This is designed to enable unit testing of other initialization measures (database, config). Please make sure you understand the flow of the program and what must be initialized in what order before you invoke this option; limited protection against out-of-order initialization has been added, but they are by no means comprehensive. """ # Table of instance variables: These are pre-defined here so that the initialize_x() methods can be used to # init the bot without loss of readability. # TODO: Comments. self.log_path = None self.db_path = None self.ini_path = None self.db = None self.logfile = None self.config = None self.client = None self.testing_mode = testing_mode # Set the bot's name (defaults to ImgurBot). Remove restricted filesystem characters while we're at it. self.name = name.translate(None, ImgurBot.restricted_filesystem_chars) # Set the bot's log level (defaults to Warning). if print_at_log_level not in ImgurBot.log_levels: print("Log level {0} is not a valid log level. Defaulting to 'Warning'.".format(str(print_at_log_level))) self.print_at_log_level = "Warning" else: self.print_at_log_level = print_at_log_level # Testing mode check: If we're in testing mode, stop here. Print the disallowed characters debug statement too. if self.testing_mode: print("Testing mode enabled; performing early termination of __init__.") if name != self.name: print("Disallowed characters removed from bot name; now '{0}'.".format(self.name)) return # Initialize the logfile at log/NAME.log for writing. self.initialize_logging() self.log("Initializing ImgurBot version {0}...".format(self.version), "Debug") if name != self.name: self.log("Disallowed characters removed from bot name; now '{0}'.".format(self.name), "Information") # Set up the SQLite database at db/NAME.db. self.initialize_database() # Set up the ConfigParser and load from ini/NAME.ini. self.initialize_config() # Initialize the client and perform authentication. self.initialize_client() self.log("Initialization of bot '{0}' complete.".format(self.name), "Debug") def __del__(self): """Deconstruct the ImgurBot.""" # Record our most up-to-date auth token. if self.config is not None and self.client is not None and self.client.auth is not None: self.config.set('credentials', 'access_token', self.client.auth.get_current_access_token()) self.write_ini_file() # Clean up the SQLite database. Note: This does not perform a commit. if self.db is not None: self.db.close() # Close the logfile. if self.logfile is not None: self.log("Successful termination of ImgurBot.", "Debug") self.logfile.close() # External / Imgur-facing methods def get_new_auth_info(self, no_file_write=False): """ Interfaces with Imgur and the user to obtain access and refresh tokens, then writes them to the .ini file. """ # No access or refresh tokens. Send them to the auth workflow. assert self.config is not None, "Out-of-order call: initialize_config must be called before get_new_auth_info." assert self.client is not None, "Out-of-order call: initialize_client must be called before get_new_auth_info." print("") print("You need to supply your PIN to obtain access and refresh tokens.") print("Go to the following URL: {0}".format(self.client.get_auth_url('pin'))) credentials = [] # Loop and obtain the correct PIN. while True: try: pin = self.get_input("Enter the PIN code from the above URL: ") credentials = self.client.authorize(pin, 'pin') print("") break except ImgurClientError as e: if str(e) == "(400) Invalid Pin": print("\nYou have entered an invalid pin. Try again.") elif str(e) == "(400) The client credentials are invalid": # offer choice: delete credentials and recreate? result = self.get_input("Your client credentials were incorrect. " + "Would you like to go through interactive bot registration? (y/N): ") if result == 'y': self.log("Moving {0} to {0}.old.".format(self.ini_path), "Information") shutil.copy(self.ini_path, "{0}.old".format(self.ini_path)) os.remove(self.ini_path) self.initialize_config() self.initialize_client() return else: self.log("Your client credentials were invalid. Correct them in {0}.".format(self.ini_path), "Error") raise self.log("Access and refresh token successfully obtained.", "Debug") # noinspection PyTypeChecker self.config.set('credentials', 'access_token', credentials['access_token']) # noinspection PyTypeChecker self.config.set('credentials', 'refresh_token', credentials['refresh_token']) if no_file_write: return self.write_ini_file() # Internal / non Imgur-facing methods def log(self, message, log_level): """Writes the given message to NAME.log, prefixed with current date and time. Ends with a newline. Also prints the message to the screen. :param log_level: A string to indicate the level of the log message. :type message: str :type log_level: str """ assert self.logfile is not None, "Out-of-order call: initialize_logging must be called before log." self.logfile.write("[{0}-{1}]: ".format(datetime.datetime.now().strftime("%c"), log_level) + message + '\n') if ImgurBot.log_levels[log_level] <= ImgurBot.log_levels[self.print_at_log_level]: print(message) def mark_seen(self, post_id): """Marks a post identified by post_id as seen. Possible exception: sqlite.IntegrityError if the post was already marked as seen. :type post_id: str """ assert self.db is not None, "Out-of-order call: initialize_database must be called before mark_seen." self.db.execute("INSERT INTO Seen(id) VALUES (?)", [post_id]) self.db.commit() def has_seen(self, post_id): """Boolean check for if the bot has seen the post identified by post_id. :type post_id: str :return: True if post_id in DB, false otherwise. """ assert self.db is not None, "Out-of-order call: initialize_database must be called before has_seen." cursor = self.db.cursor() cursor.execute("SELECT * FROM Seen WHERE id = ?", [post_id]) return cursor.fetchone() is not None def reset_seen(self, force=False): """ Delete all entries from 'Seen' table in the database. Due to the extremely destructive nature of this method, this first prints a verification message and requires user input if the 'force' variable is not set. :param force: True to skip verification message. :type force: bool """ assert self.db is not None, "Out-of-order call: initialize_database must be called before reset_seen." if not force: response = self.get_input("Are you sure you want to delete all entries from the Seen table? (y/N): ") if response != 'y': print("Canceling reset_seen.") return self.log("Deleting all entries from 'Seen' table.", "Debug") self.db.execute("DELETE FROM Seen") self.db.commit() def write_ini_file(self): self.log("Writing config file at {0}.".format(self.ini_path), "Debug") try: with open(self.ini_path, 'w') as ini_file: self.config.write(ini_file) except IOError as e: self.log("Error when writing config file at {0}: {1}: {2}\n".format(self.ini_path, str(e), str(e.args)) + "Please manually create the file with the following contents: \n" + "\n" + "[credentials]\n" + "client_id = {0}\n".format(self.config.get('credentials', 'client_id')) + "client_secret = {0}\n".format(self.config.get('credentials', 'client_secret')) + "access_token = {0}\n".format(self.config.get('credentials', 'access_token')) + "refresh_token = {0}\n".format(self.config.get('credentials', 'refresh_token')), "Error") raise # Methods used to initialize the bot. def initialize_logging(self): """Forces the creation of the log directory, then creates/opens the logfile there. Also initializes the (self.) log_path and logfile variables.""" # Broken out from __init__ to aid in testing. log_dir = ImgurBot.ensure_dir_in_cwd_exists("log") self.log_path = os.path.join(log_dir, "{0}.log".format(self.name)) self.logfile = open(self.log_path, 'a') def initialize_database(self): db_dir = ImgurBot.ensure_dir_in_cwd_exists("db") self.db_path = os.path.join(db_dir, "{0}.db".format(self.name)) try: # Inform the user that a new .db file is being created (if not previously extant). if not os.path.isfile(self.db_path): self.log("Creating database at {0}.".format(self.db_path), "Debug") # Connect and ensure that the database is set up properly. self.db = sqlite3.connect(self.db_path) cursor = self.db.cursor() cursor.execute("CREATE TABLE IF NOT EXISTS Seen(id TEXT PRIMARY KEY NOT NULL)") except sqlite3.Error as e: self.log("Error in DB setup: {0}: {1}.".format(str(e), str(e.args)), "Error") if self.db: self.db.close() raise def initialize_config(self): ini_dir = ImgurBot.ensure_dir_in_cwd_exists("ini") self.ini_path = os.path.join(ini_dir, "{0}.ini".format(self.name)) # Generate our config parser. self.config = self.get_raw_config_parser() # Test if config file exists. If not, create a template .ini file and terminate. if not os.path.isfile(self.ini_path): self.config.add_section('credentials') self.log("No .ini file was found. Beginning interactive creation.", "Debug") print("") print("To proceed, you will need a client_id and client_secret tokens, which can be obtained from Imgur at") print("the following website: https://api.imgur.com/oauth2/addclient") print("") while True: client_id = self.get_input("Enter your client_id: ") client_secret = self.get_input("Enter your client_secret: ") print("") reply = self.get_input("You entered client_id {0} and _secret {1}".format(client_id, client_secret) + ". Are these correct? (y/N): ") if reply == "y": self.config.set('credentials', 'client_id', client_id) self.config.set('credentials', 'client_secret', client_secret) break reply = self.get_input("Do you have an access and refresh token available? (y/N): ") if reply == "y": while True: access_token = self.get_input("Enter your access token: ") refresh_token = self.get_input("Enter your refresh token: ") reply = self.get_input( "You entered access token {0} and refresh token {1}".format(access_token, refresh_token) + ". Are these correct? (y/N): ") if reply == "y": self.config.set('credentials', 'access_token', access_token) self.config.set('credentials', 'refresh_token', refresh_token) break self.write_ini_file() # Point our config parser at the ini file. self.config.read(self.ini_path) def initialize_client(self): assert self.config is not None, "Out-of-order initialization: initialize_config must precede initialize_client." try: self.client = ImgurClient(self.config.get('credentials', 'client_id'), self.config.get('credentials', 'client_secret')) except (ConfigParser.NoOptionError, ConfigParser.NoSectionError) as e: self.log("Error when parsing config from {0}: {1}: {2}.".format(self.ini_path, str(e), str(e.args)), "Error") raise # Auth verification loop. while True: # Check to make sure we have access and refresh tokens; if not, have the user go through token creation. if not (self.config.has_option('credentials', 'access_token') and self.config.has_option('credentials', 'refresh_token')): self.get_new_auth_info() # Automatically checks client credential validity. # Use the access and refresh tokens read from the file / imported through account authorization. self.client.set_user_auth(self.config.get('credentials', 'access_token'), self.config.get('credentials', 'refresh_token')) # Verify that the access/refresh tokens we were supplied with are valid. try: self.client.get_account('me') except ImgurClientError as e: if str(e) == "(400) Error refreshing access token!": self.log("The supplied access and refresh tokens were invalid.", "Error") self.config.remove_option('credentials', 'access_token') self.config.remove_option('credentials', 'refresh_token') else: break # Static helper methods. @staticmethod def get_input(string): """ Get input from console regardless of python 2 or 3 From ImgurPython's examples/helpers.py file. Imported to enable 2.x and 3.x Python compatibility. :type string: str :return: The user's inputted string. """ # noinspection PyBroadException try: return raw_input(string) except: return input(string) @staticmethod def get_raw_config_parser(): """ Create a config parser for reading INI files From ImgurPython's examples/helpers.py file. Imported to enable 2.x and 3.x Python compatibility. Modified to return a RawConfigParser to enable remove_option. :return: The output of ConfigParser.ConfigParser() or configparser.ConfigParser() depending on Python version. """ # noinspection PyBroadException try: # noinspection PyUnresolvedReferences import ConfigParser return ConfigParser.RawConfigParser() except: # noinspection PyUnresolvedReferences import configparser return configparser.RawConfigParser() @staticmethod def ensure_dir_in_cwd_exists(directory): """ Guarantees that the given directory exists by creating it if not extant. Note that this removes all slashes and other filesystem-used characters from the passed-in directory parameter, and as such will only ever create directories in the current working directory. :param directory: str :return: The full OS-normalized path to the directory with no trailing slash. """ # TODO: Is stripping out sensitive characters the best way to handle it, or should we assume the user knows # ..... what they're doing? path = os.path.join(os.getcwd(), directory.translate(None, ImgurBot.restricted_filesystem_chars)) if not os.path.exists(path): try: os.makedirs(path) except OSError as e: print("Error creating directory {0}: {1}: {2}.".format(path, str(e), str(e.args[0]))) raise assert os.path.exists(path), "ensure_dir_in_cwd_exists: Directory {0} not found after creation.".format(path) return path @staticmethod def process_comment(comment): """Takes a string of arbitrary length and processes it into comment chunks that meet Imgur's 180-character requirement. If the string is <= 180 characters in length, it is returned as-is. If it is greater, it is broken up into a list of substrings such that each substring plus an indexing suffix totals no more than 180 characters in length. :param comment: A string of arbitrary length. :type comment: str :return: A list of strings. """ # TODO: Break at syllable boundary. If no valid syllable immediately before 180, break at whitespace. If no # ..... valid whitespace within X characters of 180-character boundary, break at 180-character boundary. # TeX has a useful hyphenation algorithm that we might be able to incorporate here. comment_list = [] # If the comment fits within one comment block, return as-is. if len(comment) <= 180: comment_list.append(comment) return comment_list # Calculate out the total number of comment blocks needed. suffix = ImgurBot.calculate_number_of_comment_chunks(comment) suffix_length = len(str(suffix)) # Append each comment (with " index/total" appended to it) to the comment_list. iterations = 0 while len(comment) > 0: iterations += 1 # Magic number explanation: 180 characters - (len(" ") + len("/")) = 178 characters max_len = int((180 - len(" /")) - math.ceil(math.log10(iterations + 1)) - suffix_length) comment_list.append(comment[0:max_len] + " " + str(iterations) + "/" + str(suffix)) comment = comment[max_len:] # Sanity check: We're not doing something like 4/3 or 2/3 assert iterations == suffix return comment_list @staticmethod def calculate_number_of_comment_chunks(comment): """Calculate the number of substrings generated from spitting the given comment string into Imgur-length strings of length <= 180. Includes calculation to allow each string to have a suffix that indicates its index and the total number of substrings calculated. Accelerated pre-calculation available for strings <= 171936 characters in length. For the sake of completeness, brute-force calculation is performed on strings greater than that length. Note: Explanations for pre-calculated magic numbers are provided in comments preceding the number's use. """ # Obtain the length of the comment, pre-formatted as a float to avoid truncation errors later. length = float(len(comment)) # 1584 = 9 chunks * (180 characters - len(" 1/9")) if length <= 1584: return int(math.ceil(length / 176)) # 17235 = 9 * (180 - len(" 1/99")) + (99 - 9) * (180 - len(" 10/99")) if length <= 17235: # 1575 = 9 * (180 - len(" 1/99")) # 174 = 180 - len(" 10/99") return int(9 + math.ceil((length - 1575) / 174)) # 171936 = 9 * (180-len(" 1/999")) + (99-9) * (180-len(" 10/999")) + (999-99) * (180-len(" 100/999")) if length <= 171936: # 17136 = 9 * (180-len(" 1/999")) + (99-9) * (180-len(" 10/999")) # 172 = 180 - len(" 100/999") return int(9 + 90 + math.ceil((length - 17136) / 172)) # Someone's given us a string that needs to be broken up into 1000 or more substrings... # Reserve 4 characters for the total and begin brute-force calculating how many substrings we'll need to hold # the entirety of the comment. If we have more than 9999 substrings required, reserve 5 characters and start # over, etc. # TODO: This was written for the sake of completeness, but is it even desirable to have this happen? # ..... maybe we should raise an exception instead. iterations = 0 reserved = 4 while True: iterations += 1 # Calculate the maximum allowable length for this comment chunk. # Magic number explanation: 180 - (len(" ") + len("/")) = 178 max_len = int(178 - math.ceil(math.log10(iterations + 1)) - reserved) # Ending case: The remaining text is less than or equal to our maximum length. if length <= max_len: return iterations # Edge case: We require more space to write the count of the substrings than is reserved. if math.ceil(math.log10(iterations + 1)) > reserved: reserved += 1 # Increment our reservation. iterations = 0 length = len(comment) # Start over. else: length -= max_len