Beispiel #1
0
    def __init__(self):

        if Common().db_username is not None and Common().db_password is not None and Common().db_host is not None:
            connection_string = f"{Common().db_type}://{Common().db_username}:{quote(Common().db_password)}@{Common().db_host}/?retryWrites=true&w=majority"

            self.db_client = pymongo.MongoClient(connection_string)
            self.db = self.db_client[Common().db_name]
        else:
            logging.info(
                "No Database Credentials or Database host Detected. \n Bot can't work without DB \n Exiting Bot...")
            sys.exit()
Beispiel #2
0
    async def download_book(md5: str, msg: Message):
        ack_msg = await msg.reply_text('About to download book...', quote=True)
        _, detail = await Util().get_detail(
            md5, return_fields=['extension', 'title', 'coverurl'])
        typ, _ = guess_type(detail['title'] + '.' + detail['extension'])
        book = await BookdlFiles().get_file_by_md5(md5=md5, typ=typ)

        if book:
            await BookDLBot.copy_message(chat_id=msg.chat.id,
                                         from_chat_id=book['chat_id'],
                                         message_id=book['msg_id'])
            await ack_msg.delete()
            return
        link = f'http://library.lol/main/{md5}'
        temp_dir = Path.joinpath(Common().working_dir,
                                 Path(f'{ack_msg.chat.id}+{ack_msg.id}'))
        file = await Libgen().download(
            link,
            dest_folder=temp_dir,
            progress=Downloader().download_progress_hook,
            progress_args=[ack_msg.chat.id, ack_msg.id, detail['title']])
        file_path = Path.joinpath(
            temp_dir,
            Path('[@SamfunBookdlbot] ' + sanitize(detail['title']) +
                 f'.{detail["extension"]}'))
        if Path.is_file(file):
            Path.rename(file, file_path)
        await Uploader().upload_book(
            file_path if Path.is_file(file_path) else file,
            ack_msg,
            md5,
            detail=detail)
Beispiel #3
0
 async def get_thumb(url: str, ack_msg: Message):
     file_name = os.path.basename(url)
     thumb_file = Path.joinpath(Common().working_dir,
                                Path(f'{ack_msg.chat.id}+{ack_msg.id}'),
                                Path(file_name))
     resp = requests.get(url, allow_redirects=True)
     async with aiofiles.open(thumb_file, mode='wb') as dl_file:
         await dl_file.write(resp.content)
     return thumb_file
Beispiel #4
0
    async def send_file_to_dustbin(file_message: Message, md5: str,
                                   detail: dict):
        fd_msg = await file_message.copy(chat_id=Common().bot_dustbin)

        await BookdlFiles().insert_new_files(
            title=detail['title'],
            file_name=fd_msg.document.file_name,
            msg_id=fd_msg.id,
            chat_id=fd_msg.chat.id,
            md5=md5,
            file_type=fd_msg.document.mime_type,
            coverurl=detail['coverurl'] if detail['coverurl'] else '',
            file_id=fd_msg.document.file_id)
Beispiel #5
0
 def __convert(params, extension, stat_var):
     convertapi.api_secret = Common().convert_api
     logger.info('Conversion Started...')
     try:
         result = convertapi.convert('pdf',
                                     params,
                                     from_format=extension,
                                     timeout=120)
         logger.info('Conversion Finished!')
     except ApiError as e:
         convert_status[stat_var]['Done'] = True
         logger.error('Conversion Failed!')
         raise e
     finally:
         convert_status[stat_var]['Done'] = True
     return result
Beispiel #6
0
    async def convert_to_pdf(self, md5: str, msg: Message):
        ack_msg = await msg.reply_text('About to convert book to PDF...',
                                       quote=True)
        book = await BookdlFiles().get_file_by_md5(md5=md5,
                                                   typ='application/pdf')
        if book:
            await BookDLBot.copy_message(chat_id=msg.chat.id,
                                         from_chat_id=book['chat_id'],
                                         message_id=book['msg_id'])
            await ack_msg.delete()
            return
        _, detail = await Util().get_detail(
            md5, return_fields=['mirrors', 'title', 'extension', 'coverurl'])

        temp_dir = Path.joinpath(Common().working_dir,
                                 Path(f'{ack_msg.chat.id}+{ack_msg.id}'))
        if not Path.is_dir(temp_dir):
            Path.mkdir(temp_dir)

        direct_links = await LibgenDownload().get_directlink(
            detail['mirrors']['main'])
        extension = detail['extension']
        params = {
            'File': direct_links[1],
            'PdfVersion': '2.0',
            'OpenZoom': '100',
            'PdfTitle': '@SamfunBookdlbot - ' + detail['title'],
            'RotatePage': 'ByPage'
        }
        stat_var = f"{ack_msg.chat.id}{ack_msg.id}"
        convert_status[stat_var] = {'Done': False}
        try:
            loop = asyncio.get_event_loop()
            convert_process = loop.run_in_executor(None, self.__convert,
                                                   params, extension, stat_var)
            start_time = time.time()
            while True:
                if convert_status[stat_var]['Done']:
                    break
                else:
                    try:
                        await ack_msg.edit_text(
                            f'Convertion to PDF started... {int(time.time() - start_time)}'
                        )
                    except MessageNotModified as e:
                        logger.error(e)
                    except FloodWait as e:
                        logger.error(e)
                        await asyncio.sleep(e.x)
                    await asyncio.sleep(2)
            Result = await convert_process
        except ApiError as e:
            logger.error(e)
            await ack_msg.edit_text(e)
            shutil.rmtree(temp_dir)
            return

        file_path = Path.joinpath(
            temp_dir,
            Path('[@SamfunBookdlbot] ' + sanitize(detail['title']) + '.pdf'))
        detail[
            'cost'] = f'ConvertAPI Cost: **{Result.conversion_cost}** seconds.'
        await ack_msg.edit_text(f'About to download converted file...')
        try:
            async with aiohttp.ClientSession() as dl_ses:
                async with dl_ses.get(Result.file.url) as resp:
                    total_size = int(Result.file.size)
                    file_name = Result.file.filename

                    async with aiofiles.open(file_path, mode="wb") as dl_file:
                        current = 0
                        logger.info(f'Starting download: {file_name}')
                        start_time = time.time()
                        async for chunk in resp.content.iter_chunked(1024 *
                                                                     1024):
                            await dl_file.write(chunk)
                            current += len(chunk)
                            if time.time() - start_time > 2:
                                await ack_msg.edit_text(
                                    f'Downloading: **{detail["title"]}**\n'
                                    f"Status: **{size.format_size(current, binary=True)}** of **{size.format_size(total_size, binary=True)}**"
                                )
                                start_time = time.time()
        except Exception as e:
            logger.exception(e)
            return None
        await Uploader().upload_book(file_path, ack_msg, md5, detail=detail)
Beispiel #7
0
 def __init__(self):
     convertapi.api_secret = Common().convert_api
Beispiel #8
0
"""BookDLBot Pyrogram Client."""
from pyrogram import Client
from bookdl.common import Common

BookDLBot = Client(name=Common().session_name,
                   api_id=Common().tg_api_id,
                   api_hash=Common().tg_api_hash,
                   bot_token=Common().bot_api_token,
                   workers=200,
                   workdir=Common().working_dir,
                   plugins=dict(root="bookdl/telegram/plugins"),
                   app_version="2.0",
                   device_model="BookdlBot",
                   system_version="Ubuntu/Linux",
                   in_memory=True)