class Imgur: def __init__(self, clientID, clientSecret): # to-do: error check self.client = ImgurClient(clientID, clientSecret) def uploadPhoto(self, imagePath): tempImage = self.client.upload_from_path(imagePath, config=None, anon=True) return tempImage['link'] def deletePhoto(self, imageID): self.client.delete_image(imageID)
class Imgur: def __init__(self, imgur_credentials): self.username = imgur_credentials['username'] self.client_id = imgur_credentials['client_id'] self.client_secret = imgur_credentials['client_secret'] self.access_token = imgur_credentials['access_token'] self.refresh_token = imgur_credentials['refresh_token'] self.client = ImgurClient(self.client_id, self.client_secret, self.access_token, self.refresh_token) def clean_user_images(self): items = self.client.get_account_images(self.username) success = True for item in items: if item.title == 'Instagram_DashBoard' and item.name == 'Instagram_DashBoard': res = self.client.delete_image(item.id) if not res: success = False return success def upload_image(self, path): # Here's the metadata for the upload. All of these are optional, including # this config dict itself. config = { 'album': None, 'name': 'Instagram_DashBoard', 'title': 'Instagram_DashBoard', 'description': 'pic' } print("Uploading image... ") image = self.client.upload_from_path(path, config=config, anon=False) print("Done") print() return image
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 photo_zone(object): def __init__ (self): self.obj_name = 'imgur_function' self.imgur_client_id = '33ed33e765afedc' self.imgur_client_secret = '04f0d5531b1d0978ff97fd990554c899e9e7e1f5' self.imgur_client_access_token = '85b737858a3ca32f1517bd9b8e2f5d2c5c97a647' self.imgur_client_refresh_token = '797c2292b2600815f93cc73bec6eb7c8bdbcd67e' self.API_Get_Image = 'https://otakujpbweb.herokuapp.com/api/image/random/' self.client = ImgurClient(self.imgur_client_id, self.imgur_client_secret, self.imgur_client_access_token, self.imgur_client_refresh_token) def random(self): b=self.imgur_boys g=self.beauty_girls gs=self.imgur_girls content = random.choice([b,g,b,g,b,g,g,gs]) return content() def beauty_girls(self): images = requests.get(self.API_Get_Image) url = images.json().get('Url') image_message = ImageSendMessage( original_content_url=url, preview_image_url=url ) return image_message def imgur_girls(self): return self.get_imgur_photo('23p2B') def imgur_boys(self): return self.get_imgur_photo('9eQni') def joke(self): return self.get_imgur_photo('XpG2g') def poker(self): return self.get_imgur_photo('KQjab') def gods_talk(self): return self.get_imgur_photo('6FM69') def single(self): return self.get_imgur_photo('Sy6Gm') def food(self): return self.get_imgur_photo('9rYK8') def get_imgur_photo(self,album_id): client = ImgurClient(self.imgur_client_id, self.imgur_client_secret) images = client.get_album_images(album_id) index = random.randint(0, len(images) - 1) url = images[index].link image_message = ImageSendMessage( original_content_url=url, preview_image_url=url ) return image_message def upload_imgur(self,album_id,path): #client = ImgurClient(self.imgur_client_id, self.imgur_client_secret, self.imgur_client_access_token, self.imgur_client_refresh_token) conf = {"album":album_id} res = self.client.upload_from_path(path,config=conf,anon=False) return res def imgur_album_images_delete(self,album_id): #client = ImgurClient(imgur_client_id, imgur_client_secret, imgur_client_access_token, imgur_client_refresh_token) image_list = self.client.get_album_images(album_id) for obj in image_list: self.client.delete_image(obj.id) return ("delete complete") def imgur_images_delete(self,image_id): #client = ImgurClient(imgur_client_id, imgur_client_secret, imgur_client_access_token, imgur_client_refresh_token) self.client.delete_image(image_id) return ("deleted image") def add_watermark(self,id,message_content): user_config = _sql.select_config(id) if user_config ==[]: return 'none' else: config_json = _sql.select(user_config)[0][2] config = json.loads(config_json) if config['watermark'] == {}: return 'none' else: path = 'jpg/' #path = '../jpg/' #path = '/app/jpg/' image_file = '%s%s.jpg'%(path,id) output_jpg = '%swm_%s.jpg'%(path,id) output_dir = path with open(image_file, 'wb') as fd: for chunk in message_content.iter_content(): fd.write(chunk) data = config['watermark'] #print(data) text = data['text'] fontsize = data['fontsize'] ttf = data['ttf'] color = data['color'] alpha = data['alpha'] position = data['position'] _function.add_watermark(text, int(fontsize), ttf, color, int(alpha), position, image_file, output_dir) res = self.upload_imgur('SZMo93Z',output_jpg) return res
def delete_image(deletehash, imgur_client_id, imgur_client_secret): """Attempts to delete a specific image from Imgur using its deletehash.""" client = ImgurClient(imgur_client_id, imgur_client_secret) client.delete_image(deletehash)