Exemplo n.º 1
0
def handle_images(slackRequest, latexString):
    ''' takes a latex string and uploads to imgur for the image
    '''
    imgurClientID = slackRequest.headers['Bb-Config-Imclid']
    imgurSecret = slackRequest.headers['Bb-Config-Imsec']
    logger.info(imgurClientID + '....' + imgurSecret + ' ...')

    imgur = ImgurClient(imgurClientID, imgurSecret)
    latexImageDownload = _latex_url.format(latex = latexString.replace(' ','').replace('+','%2B'))
    latexImage = requests.get(latexImageDownload).content
    data = {
            'image': base64.b64encode(latexImage),
            'type': 'base64',
            }
    imageData = imgur.make_request('POST','upload',data,True)
    latexImageLocation = imageData['link']
    return latexImageLocation    
Exemplo n.º 2
0
class ImgurStorage(Storage):
    """
    Uses the Imgur cloud service to store images.
    Great for Heroku
    
    This is just a gist, needs some work.
    """
    client_id = "LOL"
    client_secret = "LOL"
    access_token = "LOL"
    refresh_token = "LOL"

    def upload(self, path):
        return self.client.upload_from_path(path)

    def __init__(self):
        super(ImgurStorage, self).__init__()
        self.client = ImgurClient(self.client_id, self.client_secret,
                                  self.access_token, self.refresh_token)

    def _open(self, name, mode='rb'):
        file_url = "http://i.imgur.com/{0}.png".format(name)
        r = requests.get(file_url)
        f = tempfile.NamedTemporaryFile(delete=False)
        for chunk in r.iter_content(chunk_size=512 * 1024):
            if chunk:  # filter out keep-alive new chunks
                f.write(chunk)
        f.close()
        return File(f)

    def uploaded_path(self, name):
        try:
            path = safe_join(self.location, name)
        except ValueError:
            raise SuspiciousFileOperation("Attempted access to '%s' denied." %
                                          name)
        return os.path.normpath(path)

    def get_available_name(self, name):
        return name

    def _save(self, name, content):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content)

        content.open()

        data = {
            'image': base64.b64encode(content.read()),
            'type': 'base64',
            'meta': {}
        }
        ret = self.client.make_request('POST', 'upload', data, True)
        content.close()
        return ret["id"]

    def url(self, name):
        return "http://i.imgur.com/{0}.png".format(name)

    def get_valid_name(self, name):
        return name

    def exists(self, name):
        return True
Exemplo n.º 3
0
class ImgurStorage(Storage):
    """
    Uses the Imgur cloud service to store images.
    Great for Heroku
    
    This is just a gist, needs some work.
    """
    client_id = "LOL"
    client_secret = "LOL"
    access_token = "LOL"
    refresh_token = "LOL"

    def upload(self, path):
        return self.client.upload_from_path(path)

    def __init__(self):
        super(ImgurStorage, self).__init__()
        self.client = ImgurClient(self.client_id, self.client_secret, self.access_token, self.refresh_token)

    def _open(self, name, mode='rb'):
        file_url = "http://i.imgur.com/{0}.png".format(name)
        r = requests.get(file_url)
        f = tempfile.NamedTemporaryFile(delete=False)
        for chunk in r.iter_content(chunk_size=512 * 1024):
                if chunk: # filter out keep-alive new chunks
                    f.write(chunk)
        f.close()
        return File(f)

    def uploaded_path(self, name):
        try:
            path = safe_join(self.location, name)
        except ValueError:
            raise SuspiciousFileOperation("Attempted access to '%s' denied." % name)
        return os.path.normpath(path)

    def get_available_name(self, name):
        return name

    def _save(self, name, content):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content)

        content.open()

        data = {
            'image': base64.b64encode(content.read()),
            'type': 'base64',
            'meta': {}
        }
        ret = self.client.make_request('POST', 'upload', data, True)
        content.close()
        return ret["id"]

    def url(self, name):
        return "http://i.imgur.com/{0}.png".format(name)

    def get_valid_name(self, name):
        return name

    def exists(self, name):
        return True
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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