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 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_cache(self) -> Optional[ImgurClient]: # Try to authenticate with saved credentials present in auth.json. try: imgur_client = ImgurClient(**self.auth["imgur"]) imgur_client.get_account("namen") return imgur_client except Exception as e: log.exception("Could not authenticate for some reason. Fetching new access/refresh tokens.", exc_info=True) # log.info("Could not authenticate for some reason. Fetching new access/refresh tokens.") log.info("Error returned:({0.__class__.__name__}: {0}".format(e), file=sys.stderr) return 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
class ImgurStorage(Storage): """ A storage class providing access to resources in a Dropbox Public folder. """ def __init__(self, location='/'): self.client = ImgurClient( CONSUMER_ID, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_REFRESH) logger.info("Logged in Imgur storage") self.account_info = self.client.get_account(USERNAME) self.albums = self.client.get_account_albums(USERNAME) self.location = location self.base_url = 'https://api.imgur.com/3/account/{url}/'.format(url=self.account_info.url) def _get_abs_path(self, name): return os.path.join(self.location, name) def _open(self, name, mode='rb'): remote_file = self.client.get_image(name, self, mode=mode) return remote_file def _save(self, name, content): name = self._get_abs_path(name) directory = os.path.dirname(name) logger.info([a.title for a in self.albums]) logger.info(name) logger.info(directory) if not self.exists(directory) and directory: album = self.client.create_album({"title": directory}) self.albums = self.client.get_account_albums(USERNAME) album = [a for a in self.albums if a.title == directory][0] #if not response['is_dir']: # raise IOError("%s exists and is not a directory." % directory) response = self._client_upload_from_fd(content, {"album": album.id, "name": name, "title": name}, False) return response["name"] def _client_upload_from_fd(self, fd, config=None, anon=True): """ use a file descriptor to perform a make_request """ if not config: config = dict() contents = fd.read() b64 = base64.b64encode(contents) data = { 'image': b64, 'type': 'base64', } data.update({meta: config[meta] for meta in set(self.client.allowed_image_fields).intersection(config.keys())}) return self.client.make_request('POST', 'upload', data, anon) def delete(self, name): name = self._get_abs_path(name) self.client.delete_image(name) def exists(self, name): name = self._get_abs_path(name) if len([a for a in self.albums if a.title == name]) > 0: return True try: album = [a for a in self.albums if a.title == os.path.dirname(name)][0] images = self.client.get_album_images(album.id) metadata = self.client.get_image(name) if len([im for im in images if im.name == name]) > 0: logger.info(dir(metadata)) return True except ImgurClientError as e: if e.status_code == 404: # not found return False raise e except IndexError as e: return False else: return True return False def listdir(self, path): path = self._get_abs_path(path) response = self.client.get_image(path) directories = [] files = [] for entry in response.get('contents', []): if entry['is_dir']: directories.append(os.path.basename(entry['path'])) else: files.append(os.path.basename(entry['path'])) return directories, files def size(self, path): cache_key = 'django-imgur-size:%s' % filepath_to_uri(path) size = cache.get(cache_key) if not size: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] size = self.client.get_image(image.id).size cache.set(cache_key, size) return size def url(self, path): cache_key = 'django-imgur-url:%s' % filepath_to_uri(path) url = cache.get(cache_key) if not url: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] url = self.client.get_image(image.id).link cache.set(cache_key, url) return url def get_available_name(self, name, max_length=None): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ #name = self._get_abs_path(name) #dir_name, file_name = os.path.split(name) #file_root, file_ext = os.path.splitext(file_name) ## If the filename already exists, add an underscore and a number (before ## the file extension, if one exists) to the filename until the generated ## filename doesn't exist. #count = itertools.count(1) #while self.exists(name): # # file_ext includes the dot. # name = os.path.join(dir_name, "%s_%s%s" % (file_root, count.next(), file_ext)) return name
class ImgurStorage(Storage): """ A storage class providing access to resources in a Dropbox Public folder. """ def __init__(self, location='/'): self.client = ImgurClient(CONSUMER_ID, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_REFRESH) logger.info("Logged in Imgur storage") self.account_info = self.client.get_account(USERNAME) self.albums = self.client.get_account_albums(USERNAME) self.location = location self.base_url = 'https://api.imgur.com/3/account/{url}/'.format( url=self.account_info.url) def _get_abs_path(self, name): return os.path.join(self.location, name) def _open(self, name, mode='rb'): remote_file = self.client.get_image(name, self, mode=mode) return remote_file def _save(self, name, content): name = self._get_abs_path(name) directory = os.path.dirname(name) logger.info([a.title for a in self.albums]) logger.info(name) logger.info(directory) if not self.exists(directory) and directory: album = self.client.create_album({"title": directory}) self.albums = self.client.get_account_albums(USERNAME) album = [a for a in self.albums if a.title == directory][0] #if not response['is_dir']: # raise IOError("%s exists and is not a directory." % directory) response = self._client_upload_from_fd(content, { "album": album.id, "name": name, "title": name }, False) return response["name"] def _client_upload_from_fd(self, fd, config=None, anon=True): """ use a file descriptor to perform a make_request """ if not config: config = dict() contents = fd.read() b64 = base64.b64encode(contents) data = { 'image': b64, 'type': 'base64', } data.update({ meta: config[meta] for meta in set(self.client.allowed_image_fields).intersection( list(config.keys())) }) return self.client.make_request('POST', 'upload', data, anon) def delete(self, name): name = self._get_abs_path(name) self.client.delete_image(name) def exists(self, name): name = self._get_abs_path(name) if len([a for a in self.albums if a.title == name]) > 0: return True try: album = [ a for a in self.albums if a.title == os.path.dirname(name) ][0] images = self.client.get_album_images(album.id) metadata = self.client.get_image(name) if len([im for im in images if im.name == name]) > 0: logger.info(dir(metadata)) return True except ImgurClientError as e: if e.status_code == 404: # not found return False raise e except IndexError as e: return False else: return True return False def listdir(self, path): path = self._get_abs_path(path) response = self.client.get_image(path) directories = [] files = [] for entry in response.get('contents', []): if entry['is_dir']: directories.append(os.path.basename(entry['path'])) else: files.append(os.path.basename(entry['path'])) return directories, files def size(self, path): cache_key = 'django-imgur-size:%s' % filepath_to_uri(path) size = cache.get(cache_key) if not size: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] size = self.client.get_image(image.id).size cache.set(cache_key, size) return size def url(self, path): cache_key = 'django-imgur-url:%s' % filepath_to_uri(path) url = cache.get(cache_key) if not url: directory = os.path.dirname(path) name = os.path.basename(path) album = [a for a in self.albums if a.title == directory][0] images = self.client.get_album_images(album.id) image = [im for im in images if im.name == path][0] url = self.client.get_image(image.id).link cache.set(cache_key, url) return url def get_available_name(self, name, max_length=None): """ Returns a filename that's free on the target storage system, and available for new content to be written to. """ #name = self._get_abs_path(name) #dir_name, file_name = os.path.split(name) #file_root, file_ext = os.path.splitext(file_name) ## If the filename already exists, add an underscore and a number (before ## the file extension, if one exists) to the filename until the generated ## filename doesn't exist. #count = itertools.count(1) #while self.exists(name): # # file_ext includes the dot. # name = os.path.join(dir_name, "%s_%s%s" % (file_root, count.next(), file_ext)) return name
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
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)