コード例 #1
0
 def download_picture(self, picture_url: str, album_folder: str) -> None:
     """
 Download picture.
 :param picture_url: picture url
 :param album_folder: folder path
 """
     try:
         if picture_url.startswith('//'):
             picture_url = picture_url.replace('//', '', 1)
         picture_name = picture_url.rsplit('/', 1)[1]
         picture_path = os.path.join(album_folder, picture_name)
         if not os.path.exists(picture_path):
             logger.info(f'Start downloading: {picture_url}')
             retry = 1
             response = requests.get(picture_url,
                                     stream=True,
                                     timeout=self.timeout)
             while response.status_code != 200 and retry <= self.retries:
                 logger.warning(f'{retry}º Retry: {picture_name}')
                 response = requests.get(picture_url,
                                         stream=True,
                                         timeout=self.timeout)
                 retry += 1
             if len(response.content) > 0:
                 with open(picture_path, 'wb') as image:
                     image.write(response.content)
                     logger.log(5, f'Completed download of: {picture_name}')
             else:
                 raise Exception('Zero content')
         else:
             logger.warning(f'Picture already exists: {picture_name} ')
     except Exception as e:
         logger.error(f'Failed to download picture: {picture_url}\n{e}')
コード例 #2
0
ファイル: album.py プロジェクト: Lucas8x/luscious-downloader
 def fetch_info(self) -> bool:
     """
 Fetch album information.
 :return: bool - true if there are no error otherwise false
 """
     logger.log(5, 'Fetching album information...')
     response = requests.post(
         'https://members.luscious.net/graphql/nobatch/?operationName=AlbumGet',
         json=album_info_query(str(self.id_))).json()
     data = response['data']['album']['get']
     if 'errors' in data:
         logger.error(
             f'Something wrong with album: {self.id_}\nErrors: {data["errors"]}'
         )
         logger.warning('Skipping...')
         return False
     self.title = data['title']
     self.author = data['created_by']['display_name']
     self.number_of_pictures = data['number_of_pictures']
     self.number_of_animated_pictures = data['number_of_animated_pictures']
     self.info.update({
         'slug':
         data.get('slug', self.title),
         'language':
         data.get('language', {}).get('title', ''),
         'tags': [tag.get('text', '') for tag in data.get('tags', {})],
         'genres':
         [genre.get('title', '') for genre in data.get('genres', {})],
         'audiences': [
             audience.get('title', '')
             for audience in data.get('audiences', {})
         ],
     })
     return True
コード例 #3
0
 def download_picture(self, picture_url: str, album_folder: Path) -> None:
     """
 Download picture.
 :param picture_url: picture url
 :param album_folder: album folder path
 """
     try:
         picture_url = normalize_url(picture_url)
         picture_name = picture_url.rsplit('/', 1)[1]
         picture_path = Path.joinpath(album_folder, picture_name)
         if not Path.exists(picture_path):
             logger.info(f'Start downloading: {picture_url}')
             retry = 1
             response = requests.get(picture_url,
                                     stream=True,
                                     timeout=self.timeout)
             while response.status_code != 200 and retry <= self.retries:
                 logger.warning(f'{retry}º Retry: {picture_name}')
                 response = requests.get(picture_url,
                                         stream=True,
                                         timeout=self.timeout)
                 retry += 1
             if retry > self.retries:
                 raise Exception('Reached maximum number of retries')
             if len(response.content) > 0:
                 with picture_path.open('wb') as image:
                     image.write(response.content)
                     logger.log(5, f'Completed download of: {picture_name}')
             else:
                 raise Exception('Zero content')
         else:
             logger.warning(f'Picture already exists: {picture_name} ')
     except Exception as e:
         logger.error(f'Failed to download picture: {picture_url}\n{e}')
コード例 #4
0
def create_folder(directory):
    try:
        if not os.path.exists(directory):
            os.makedirs(directory)
            logger.info(f'Album folder created: {directory}')
        else:
            logger.warn(f'Album folder {directory} already exist.')
    except OSError:
        logger.error(f'Creating directory: {directory}\n{e}')
コード例 #5
0
ファイル: utils.py プロジェクト: Lucas8x/luscious-downloader
def create_folder(directory: Path) -> None:
  """
  Creates folder in the specified path.
  :param directory: folder path
  """
  try:
    if not Path.exists(directory):
      Path.mkdir(directory, parents=True, exist_ok=True)
      logger.info(f'Album folder created in: {directory}')
    else:
      logger.warn(f'Album folder already exist in: {directory}')
  except Exception as e:
    logger.error(f'Create folder: {e}')
コード例 #6
0
def create_folder(directory: str) -> None:
  """
  Creates folder in the specified path.
  :param directory: folder path
  """
  try:
    if not os.path.exists(directory):
      os.makedirs(directory, exist_ok=True)
      logger.info(f'Album folder created in: {directory}')
    else:
      logger.warn(f'Album folder already exist in: {directory}')
  except OSError:
    logger.error(f'Creating directory in: {directory}')
コード例 #7
0
ファイル: utils.py プロジェクト: Lucas8x/luscious-downloader
def generate_pdf(output_dir: Path, formmatted_name: str, album_folder: Path, rm_origin_dir=False) -> None:
  """
  Create pdf file containing album pictures [jpg,jpeg].
  :param output_dir: output folder path
  :param formmatted_name: formmatted album name
  :param album_folder: album folder path
  :param rm_origin_dir: indicates whether the source folder will be deleted
  """
  try:
    from PIL import Image
    logger.info('Generating album pdf file...')

    pictures_path_list = []
    for file_name in album_folder.iterdir():
      if file_name.suffix.lower() not in ['.jpg', '.jpeg', '.png']:
        continue
      picture_path = Path.joinpath(album_folder, file_name)
      if picture_path.is_dir():
        continue
      pictures_path_list.append(picture_path)

    pictures = []
    if len(pictures_path_list) > 0:
      for picture_path in pictures_path_list:
        img = Image.open(picture_path)
        if picture_path.suffix.lower() == '.png' or img.mode == 'RGBA':
          img = img.convert('RGB')
        pictures.append(img)

    if len(pictures) == 0:
      raise Exception('Pictures list is empty, probably has no valid images [jpg, jpeg, png]')

    pdf_filename = f'{formmatted_name}.pdf'
    pdf_path = Path.joinpath(output_dir, pdf_filename)

    logger.info(f'Adding {len(pictures)} pictures to pdf...')

    pictures[0].save(pdf_path, save_all=True, append_images=pictures[1:])
    logger.log(5, f'Album PDF saved to: {output_dir}')

    for img in pictures:
      img.close()

    if rm_origin_dir:
      shutil.rmtree(album_folder, ignore_errors=True)
      logger.log(5, f'Album {formmatted_name} folder deleted.')

  except ImportError:
    logger.error('Please install Pillow package by using pip.')
  except Exception as e:
    logger.error(f'Failed to generate album pdf: {e}')
コード例 #8
0
ファイル: user.py プロジェクト: Lucas8x/luscious-downloader
 def fetch_info(self) -> bool:
     """
 Fetch user information.
 :return: bool - true if there are no error otherwise false
 """
     logger.log(5, 'Fetching user information...')
     response = requests.post(
         'https://members.luscious.net/graphql/nobatch/?operationName=ProfileGet',
         json=user_info_query(str(self.id_))).json()
     data = response['data']['userprofile']['get']
     if "errors" in data:
         logger.error(
             f'Something wrong with user: {self.id_}\nErrors: {data["errors"]}'
         )
         logger.warning('Skipping...')
         return False
     self.name = data['user']['name']
     self.number_of_albums = data['number_of_albums']
     self.number_of_favorites = data['number_of_favorite_albums']
     return True
コード例 #9
0
 def fetch_info(self) -> bool:
     """
 Fetch album information.
 :return: bool - true if there are no error otherwise false
 """
     logger.log(5, 'Fetching album information...')
     response = requests.post(
         'https://members.luscious.net/graphql/nobatch/?operationName=AlbumGet',
         json=album_info_query(str(self.id_))).json()
     data = response['data']['album']['get']
     if 'errors' in data:
         logger.error(
             f'Something wrong with album: {self.id_}\nErrors: {data["errors"]}'
         )
         logger.warning('Skipping...')
         return False
     self.title = data['title']
     self.author = data['created_by']['display_name']
     self.number_of_pictures = data['number_of_pictures']
     self.number_of_animated_pictures = data['number_of_animated_pictures']
     return True
コード例 #10
0
def download_picture(picture_url, directory, album_name):
    try:
        picture_name = picture_url.rsplit('/', 1)[1]
        picture_path = f'{directory}{album_name}/{picture_name}'
        if not (os.path.exists(picture_path)):
            logger.info(f'Start downloading: {picture_url}')
            retries = 1
            res = requests.get(picture_url, stream=True)
            while res.status_code != 200 and retries <= 5:
                logger.warning(f'{retries}º Retry: {picture_name}')
                res = requests.get(picture_url, stream=True)
            if len(res.content) > 0:
                with open(picture_path, 'wb') as image:
                    image.write(res.content)
                    logger.log(5, f'Completed download of: {picture_name}')
            else:
                raise Exception('Zero content')
        else:
            logger.warning(f'Picture: {picture_name} already exist.')
    except Exception as e:
        logger.error(f'Failed to download picture: {picture_url}\n{e}')