Пример #1
0
def cloneNode(update, context):
    args = update.message.text.split(" ", maxsplit=1)
    if len(args) > 1:
        link = args[1]
        gd = GoogleDriveHelper()
        if CLONE_LIMIT is not None or STOP_DUPLICATE_CLONE:
            msg1 = sendMessage(f"Checking Your Link...", context.bot, update)
            res, clonesize, name = gd.clonehelper(link)
            if res != "":
                deleteMessage(context.bot, msg1)
                sendMessage(res, context.bot, update)
                return
            if STOP_DUPLICATE_CLONE:
                LOGGER.info(f"Checking File/Folder if already in Drive...")
                smsg, button = gd.drive_list(name)
                if smsg:
                    deleteMessage(context.bot, msg1)
                    msg3 = "File/Folder is already available in Drive.\nHere are the search results:"
                    sendMarkup(msg3, context.bot, update, button)
                    return
                else:
                    if CLONE_LIMIT is None:
                        deleteMessage(context.bot, msg1)
            if CLONE_LIMIT is not None:
                LOGGER.info(f"Checking File/Folder Size...")
                limit = CLONE_LIMIT
                limit = limit.split(' ', maxsplit=1)
                limitint = int(limit[0])
                msg2 = f'Failed, Clone limit is {CLONE_LIMIT}.\nYour File/Folder size is {get_readable_file_size(clonesize)}.'
                if 'GB' in limit or 'gb' in limit:
                    if clonesize > limitint * 1024**3:
                        deleteMessage(context.bot, msg1)
                        sendMessage(msg2, context.bot, update)
                        return
                    else:
                        deleteMessage(context.bot, msg1)
                elif 'TB' in limit or 'tb' in limit:
                    if clonesize > limitint * 1024**4:
                        deleteMessage(context.bot, msg1)
                        sendMessage(msg2, context.bot, update)
                        return
                    else:
                        deleteMessage(context.bot, msg1)
        msg = sendMessage(f"Cloning: <code>{link}</code>", context.bot, update)
        result, button = gd.clone(link)
        deleteMessage(context.bot, msg)
        if button == "":
            sendMessage(result, context.bot, update)
        else:
            if update.message.from_user.username:
                uname = f'@{update.message.from_user.username}'
            else:
                uname = f'<a href="tg://user?id={update.message.from_user.id}">{update.message.from_user.first_name}</a>'
            if uname is not None:
                cc = f'\n\ncc: {uname}'
            sendMarkup(result + cc, context.bot, update, button)
    else:
        sendMessage('Provide G-Drive Shareable Link to Clone.', context.bot,
                    update)
Пример #2
0
def list_buttons(update, context):
    user_id = update.message.from_user.id
    if len(update.message.text.split(" ", maxsplit=1)) < 2:
        return sendMessage('Send a search key along with command', context.bot, update)
    buttons = button_build.ButtonMaker()
    buttons.sbutton("Drive Root", f"types {user_id} root")
    buttons.sbutton("Recursive", f"types {user_id} recu")
    buttons.sbutton("Cancel", f"types {user_id} cancel")
    button = InlineKeyboardMarkup(buttons.build_menu(2))
    sendMarkup('Choose option to list.', context.bot, update, button)
Пример #3
0
 def onUploadComplete(self, link: str, size):
     with download_dict_lock:
         msg = f"<b>Filename : </b><code>{download_dict[self.uid].name()}</code>\n<b>Size : </b><code>{size}</code>"
         buttons = button_build.ButtonMaker()
         if SHORTENER is not None and SHORTENER_API is not None:
             surl = requests.get(
                 f"https://{SHORTENER}/api?api={SHORTENER_API}&url={link}&format=text"
             ).text
             buttons.buildbutton("Drive Link", surl)
         else:
             buttons.buildbutton("Drive Link", link)
         LOGGER.info(f"Done Uploading {download_dict[self.uid].name()}")
         if INDEX_URL is not None:
             url_path = requests.utils.quote(
                 f"{download_dict[self.uid].name()}")
             share_url = f"{INDEX_URL}/{url_path}"
             if os.path.isdir(
                     f"{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}"
             ):
                 share_url += "/"
             if SHORTENER is not None and SHORTENER_API is not None:
                 siurl = requests.get(
                     f"https://{SHORTENER}/api?api={SHORTENER_API}&url={share_url}&format=text"
                 ).text
                 buttons.buildbutton("Index Link", siurl)
             else:
                 buttons.buildbutton("Index Link", share_url)
         if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None:
             buttons.buildbutton(f"{BUTTON_THREE_NAME}",
                                 f"{BUTTON_THREE_URL}")
         if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:
             buttons.buildbutton(f"{BUTTON_FOUR_NAME}",
                                 f"{BUTTON_FOUR_URL}")
         if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:
             buttons.buildbutton(f"{BUTTON_FIVE_NAME}",
                                 f"{BUTTON_FIVE_URL}")
         if self.message.from_user.username:
             uname = f"@{self.message.from_user.username}"
         else:
             uname = f'<a href="tg://user?id={self.message.from_user.id}">{self.message.from_user.first_name}</a>'
         if uname is not None:
             msg += f"\n\ncc : {uname}"
         try:
             fs_utils.clean_download(download_dict[self.uid].path())
         except FileNotFoundError:
             pass
         del download_dict[self.uid]
         count = len(download_dict)
     sendMarkup(msg, self.bot, self.update,
                InlineKeyboardMarkup(buttons.build_menu(2)))
     if count == 0:
         self.clean()
     else:
         update_all_messages()
Пример #4
0
def cloneNode(update,context):
    args = update.message.text.split(" ",maxsplit=1)
    if len(args) > 1:
        link = args[1]
        msg = sendMessage(f"Cloning: <code>{link}</code>",context.bot,update)
        gd = GoogleDriveHelper()
        result, button = gd.clone(link)
        deleteMessage(context.bot,msg)
        if button == "":
            sendMessage(result,context.bot,update)
        else:
            sendMarkup(result,context.bot,update,button)
    else:
        sendMessage("Provide G-Drive Shareable Link to Clone.",context.bot,update)
Пример #5
0
def list_drive(update, context):
    try:
        search = update.message.text.split(' ', maxsplit=1)[1]
        LOGGER.info(f"Searching: {search}")
        gdrive = GoogleDriveHelper(None)
        msg, button = gdrive.drive_list(search)

        if button:
            sendMarkup(msg, context.bot, update, button)
        else:
            sendMessage('No result found', context.bot, update)

    except IndexError:
        sendMessage('send a search key along with command', context.bot,
                    update)
Пример #6
0
def cloneNode(update, context):
    args = update.message.text.split(" ", maxsplit=1)
    if len(args) > 1:
        link = args[1]
        gd = GoogleDriveHelper()
        if CLONE_LIMIT is not None or STOP_DUPLICATE_CLONE:
            res, clonesize, name = gd.clonehelper(link)
            if res != "":
                sendMessage(res, context.bot, update)
                return
            if STOP_DUPLICATE_CLONE:
                LOGGER.info(f"🔎 Checking File/Folder if already in Drive...")
                smsg, button = gd.drive_list(name)
                if smsg:
                    msg3 = "File/Folder is already available in Drive.\nHere are the search results:"
                    sendMarkup(msg3, context.bot, update, button)
                    return
            if CLONE_LIMIT is not None:
                LOGGER.info(f"Checking File/Folder Size...")
                limit = CLONE_LIMIT
                limit = limit.split(' ', maxsplit=1)
                limitint = int(limit[0])
                msg2 = f'Failed, Clone limit is {CLONE_LIMIT}.\nYour File/Folder size is {get_readable_file_size(clonesize)}.'
                if 'G' in limit[1] or 'g' in limit[1]:
                    if clonesize > limitint * 1024**3:
                        sendMessage(msg2, context.bot, update)
                        return
                elif 'T' in limit[1] or 't' in limit[1]:
                    if clonesize > limitint * 1024**4:
                        sendMessage(msg2, context.bot, update)
                        return
        msg = sendMessage(f"📚 Cloning : <code>{link}</code>", context.bot,
                          update)
        result, button = gd.clone(link)
        deleteMessage(context.bot, msg)
        if button == "":
            sendMessage(result, context.bot, update)
        else:
            if update.message.from_user.username:
                uname = f'@{update.message.from_user.username}'
            else:
                uname = f'<a href="tg://user?id={update.message.from_user.id}">{update.message.from_user.first_name}</a>'
            if uname is not None:
                cc = f'\n\n👤 𝗖𝗹𝗼𝗻𝗲𝗿 : {uname}\n\n🔥 𝗣𝗿𝗶𝗶𝗶𝗶𝘆𝗼 𝗠𝗶𝗿𝗿𝗼𝗿 𝗭𝗼𝗻𝗘\n\n🔥 𝗚𝗿𝗼𝘂𝗽 : @PriiiiyoMirror\n\n▫️#Uploaded To Team Drive ✓ \n\n🚫 𝗗𝗼 𝗡𝗼𝘁 𝗦𝗵𝗮𝗿𝗲 𝗜𝗻𝗱𝗲𝘅 𝗟𝗶𝗻𝗸 \n\n✅ 𝗣𝗼𝘄𝗲𝗿𝗲𝗱 𝗕𝘆 : @PriiiiyoBOTs'
            sendMarkup(result + cc, context.bot, update, button)
    else:
        sendMessage('Provide G-Drive Shareable Link to Clone.', context.bot,
                    update)
Пример #7
0
def __onDownloadStarted(api, gid):
    try:
        if any([
                STOP_DUPLICATE, TORRENT_DIRECT_LIMIT, ZIP_UNZIP_LIMIT,
                STORAGE_THRESHOLD
        ]):
            sleep(1.5)
            dl = getDownloadByGid(gid)
            if dl is None:
                return
            download = api.get_download(gid)
            if STOP_DUPLICATE and not dl.getListener().isLeech:
                LOGGER.info('Checking File/Folder if already in Drive...')
                sname = download.name
                if dl.getListener().isZip:
                    sname = sname + ".zip"
                elif dl.getListener().extract:
                    try:
                        sname = get_base_name(sname)
                    except:
                        sname = None
                if sname is not None:
                    smsg, button = GoogleDriveHelper().drive_list(sname, True)
                    if smsg:
                        dl.getListener().onDownloadError(
                            'File/Folder already available in Drive.\n\n')
                        api.remove([download], force=True, files=True)
                        return sendMarkup("Here are the search results:",
                                          dl.getListener().bot,
                                          dl.getListener().update, button)
            if any([ZIP_UNZIP_LIMIT, TORRENT_DIRECT_LIMIT, STORAGE_THRESHOLD]):
                sleep(1)
                limit = None
                size = api.get_download(gid).total_length
                arch = any([dl.getListener().isZip, dl.getListener().extract])
                if STORAGE_THRESHOLD is not None:
                    acpt = check_storage_threshold(size, arch, True)
                    # True if files allocated, if allocation disabled remove True arg
                    if not acpt:
                        msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.'
                        msg += f'\nYour File/Folder size is {get_readable_file_size(size)}'
                        dl.getListener().onDownloadError(msg)
                        return api.remove([download], force=True, files=True)
                if ZIP_UNZIP_LIMIT is not None and arch:
                    mssg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB'
                    limit = ZIP_UNZIP_LIMIT
                elif TORRENT_DIRECT_LIMIT is not None:
                    mssg = f'Torrent/Direct limit is {TORRENT_DIRECT_LIMIT}GB'
                    limit = TORRENT_DIRECT_LIMIT
                if limit is not None:
                    LOGGER.info('Checking File/Folder Size...')
                    if size > limit * 1024**3:
                        dl.getListener().onDownloadError(
                            f'{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}'
                        )
                        return api.remove([download], force=True, files=True)
    except:
        LOGGER.error(
            f"onDownloadStart: {gid} stop duplicate and size check didn't pass"
        )
Пример #8
0
def cloneNode(update, context):
    args = update.message.text.split(" ", maxsplit=1)
    if len(args) > 1:
        link = args[1]
        gd = GoogleDriveHelper()
        if CLONE_LIMIT is not None:
            mssg = sendMessage(f"Checking The Size...", context.bot, update)
            limit = CLONE_LIMIT
            limit = limit.split(' ', maxsplit=1)
            limitint = int(limit[0])
            res, clonesizelimit = gd.count(link)
            if clonesizelimit != "":
                msgg = f'Failed, Clone limit is {CLONE_LIMIT}'
                if 'GB' in limit or 'gb' in limit:
                    if clonesizelimit > limitint * 1024**3:
                        deleteMessage(context.bot, mssg)
                        sendMessage(msgg, context.bot, update)
                        return
                    else:
                        deleteMessage(context.bot, mssg)
                elif 'TB' in limit or 'tb' in limit:
                    if clonesizelimit > limitint * 1024**4:
                        deleteMessage(context.bot, mssg)
                        sendMessage(msgg, context.bot, update)
                        return
                    else:
                        deleteMessage(context.bot, mssg)
            else:
                deleteMessage(context.bot, mssg)
                sendMessage(res, context.bot, update)
                return
        msg = sendMessage(f"Cloning: <code>{link}</code>", context.bot, update)
        result, button = gd.clone(link)
        deleteMessage(context.bot, msg)
        if button == "":
            sendMessage(result, context.bot, update)
        else:
            if update.message.from_user.username:
                uname = f'@{update.message.from_user.username}'
            else:
                uname = f'<a href="tg://user?id={update.message.from_user.id}">{update.message.from_user.first_name}</a>'
            if uname is not None:
                cc = f'\n\n#cc: {uname}'
            sendMarkup(result + cc, context.bot, update, button)
    else:
        sendMessage('Provide G-Drive Shareable Link to Clone.', context.bot,
                    update)
Пример #9
0
def add_mega_download(mega_link: str, path: str, listener):
    executor = AsyncExecutor()
    api = MegaApi(MEGA_API_KEY, None, None, 'mirror-leech-telegram-bot')
    mega_listener = MegaAppListener(executor.continue_event, listener)
    global listeners
    api.addListener(mega_listener)
    listeners.append(mega_listener)
    if MEGA_EMAIL_ID is not None and MEGA_PASSWORD is not None:
        executor.do(api.login, (MEGA_EMAIL_ID, MEGA_PASSWORD))
    link_type = get_mega_link_type(mega_link)
    if link_type == "file":
        LOGGER.info(
            "File. If your download didn't start, then check your link if it's available to download"
        )
        executor.do(api.getPublicNode, (mega_link, ))
        node = mega_listener.public_node
    else:
        LOGGER.info(
            "Folder. If your download didn't start, then check your link if it's available to download"
        )
        folder_api = MegaApi(MEGA_API_KEY, None, None, 'mltb')
        folder_api.addListener(mega_listener)
        executor.do(folder_api.loginToFolder, (mega_link, ))
        node = folder_api.authorizeNode(mega_listener.node)
    if mega_listener.error is not None:
        return sendMessage(str(mega_listener.error), listener.bot,
                           listener.update)
    if STOP_DUPLICATE and not listener.isLeech:
        LOGGER.info('Checking File/Folder if already in Drive')
        mname = node.getName()
        if listener.isZip:
            mname = mname + ".zip"
        if not listener.extract:
            smsg, button = GoogleDriveHelper().drive_list(mname, True)
            if smsg:
                msg1 = "File/Folder is already available in Drive.\nHere are the search results:"
                return sendMarkup(msg1, listener.bot, listener.update, button)
    limit = None
    if ZIP_UNZIP_LIMIT is not None and (listener.isZip or listener.extract):
        msg3 = f'Failed, Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
        limit = ZIP_UNZIP_LIMIT
    elif MEGA_LIMIT is not None:
        msg3 = f'Failed, Mega limit is {MEGA_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
        limit = MEGA_LIMIT
    if limit is not None:
        LOGGER.info('Checking File/Folder Size...')
        size = api.getSize(node)
        if size > limit * 1024**3:
            return sendMessage(msg3, listener.bot, listener.update)
    with download_dict_lock:
        download_dict[listener.uid] = MegaDownloadStatus(
            mega_listener, listener)
    makedirs(path)
    gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                string.digits,
                                                k=8))
    mega_listener.setValues(node.getName(), api.getSize(node), gid)
    sendStatusMessage(listener.update, listener.bot)
    executor.do(api.startDownload, (node, path))
Пример #10
0
def __onDownloadStarted(api, gid):
    if STOP_DUPLICATE or TORRENT_DIRECT_LIMIT is not None or ZIP_UNZIP_LIMIT is not None:
        sleep(1.5)
        dl = getDownloadByGid(gid)
        download = api.get_download(gid)
        try:
            if STOP_DUPLICATE and dl is not None and not dl.getListener(
            ).isLeech:
                LOGGER.info('Checking File/Folder if already in Drive...')
                sname = download.name
                if dl.getListener().isZip:
                    sname = sname + ".zip"
                if not dl.getListener().extract:
                    smsg, button = GoogleDriveHelper().drive_list(sname, True)
                    if smsg:
                        dl.getListener().onDownloadError(
                            'File/Folder already available in Drive.\n\n')
                        api.remove([download], force=True, files=True)
                        sendMarkup("Here are the search results:",
                                   dl.getListener().bot,
                                   dl.getListener().update, button)
                        return
            if dl is not None and (ZIP_UNZIP_LIMIT is not None
                                   or TORRENT_DIRECT_LIMIT is not None):
                sleep(1)
                limit = None
                if ZIP_UNZIP_LIMIT is not None and (dl.getListener().isZip or
                                                    dl.getListener().extract):
                    mssg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB'
                    limit = ZIP_UNZIP_LIMIT
                elif TORRENT_DIRECT_LIMIT is not None:
                    mssg = f'Torrent/Direct limit is {TORRENT_DIRECT_LIMIT}GB'
                    limit = TORRENT_DIRECT_LIMIT
                if limit is not None:
                    LOGGER.info('Checking File/Folder Size...')
                    size = api.get_download(gid).total_length
                    if size > limit * 1024**3:
                        dl.getListener().onDownloadError(
                            f'{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}'
                        )
                        api.remove([download], force=True, files=True)
                        return
        except:
            LOGGER.error(
                f"onDownloadStart: {gid} stop duplicate and size check didn't pass"
            )
    def add_download(self, message, path, filename):
        _message = self._bot.get_messages(message.chat.id, message.message_id)
        media = None
        media_array = [_message.document, _message.video, _message.audio]
        for i in media_array:
            if i is not None:
                media = i
                break
        if media is not None:
            with global_lock:
                # For avoiding locking the thread lock for long time unnecessarily
                download = media.file_id not in GLOBAL_GID
            if filename == "":
                name = media.file_name
            else:
                name = filename
                path = path + name

            if download:
                if STOP_DUPLICATE_MIRROR:
                    LOGGER.info(f"Checking File/Folder if already in Drive...")
                    if self.__listener.isTar:
                        name = name + ".tar"
                    if self.__listener.extract:
                        smsg = None
                    else:
                        gd = GoogleDriveHelper()
                        smsg, button = gd.drive_list(name)
                    if smsg:
                        self.__onDownloadError(
                            'File/Folder is already available in Drive.\n\n')
                        sendMarkup("Here are the search results:",
                                   self.__listener.bot, self.__listener.update,
                                   button)
                        return
                sendStatusMessage(self.__listener.update, self.__listener.bot)
                self.__onDownloadStart(name, media.file_size, media.file_id)
                LOGGER.info(
                    f'Downloading Telegram file with id: {media.file_id}')
                threading.Thread(target=self.__download,
                                 args=(_message, path)).start()
            else:
                self.__onDownloadError('File already being downloaded!')
        else:
            self.__onDownloadError('No document in the replied message')
Пример #12
0
    def add_download(self, message, path, filename):
        _message = app.get_messages(message.chat.id,
                                    reply_to_message_ids=message.message_id)
        media = None
        media_array = [_message.document, _message.video, _message.audio]
        for i in media_array:
            if i is not None:
                media = i
                break
        if media is not None:
            with global_lock:
                # For avoiding locking the thread lock for long time unnecessarily
                download = media.file_id not in GLOBAL_GID
            if filename == "":
                name = media.file_name
            else:
                name = filename
                path = path + name

            if download:
                size = media.file_size
                if STOP_DUPLICATE and not self.__listener.isLeech:
                    LOGGER.info('Checking File/Folder if already in Drive...')
                    smsg, button = GoogleDriveHelper().drive_list(
                        name, True, True)
                    if smsg:
                        msg = "File/Folder is already available in Drive.\nHere are the search results:"
                        return sendMarkup(msg, self.__listener.bot,
                                          self.__listener.update, button)
                if STORAGE_THRESHOLD is not None:
                    arch = any(
                        [self.__listener.isZip, self.__listener.extract])
                    acpt = check_storage_threshold(size, arch)
                    if not acpt:
                        msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.'
                        msg += f'\nYour File/Folder size is {get_readable_file_size(size)}'
                        return sendMessage(msg, self.__listener.bot,
                                           self.__listener.update)
                self.__onDownloadStart(name, size, media.file_id)
                LOGGER.info(
                    f'Downloading Telegram file with id: {media.file_id}')
                Thread(target=self.__download, args=(_message, path)).start()
            else:
                self.__onDownloadError('File already being downloaded!')
        else:
            self.__onDownloadError('No document in the replied message')
Пример #13
0
def add_gd_download(link, listener, is_gdtot):
    res, size, name, files = GoogleDriveHelper().helper(link)
    if res != "":
        return sendMessage(res, listener.bot, listener.update)
    if STOP_DUPLICATE and not listener.isLeech:
        LOGGER.info('Checking File/Folder if already in Drive...')
        if listener.isZip:
            gname = name + ".zip"
        elif listener.extract:
            try:
                gname = get_base_name(name)
            except:
                gname = None
        if gname is not None:
            gmsg, button = GoogleDriveHelper().drive_list(gname, True)
            if gmsg:
                msg = "File/Folder is already available in Drive.\nHere are the search results:"
                return sendMarkup(msg, listener.bot, listener.update, button)
    if STORAGE_THRESHOLD is not None:
        acpt = check_storage_threshold(size, True)
        if not acpt:
            msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.'
            msg += f'\nYour File/Folder size is {get_readable_file_size(size)}'
            return sendMessage(msg, listener.bot, listener.update)
    if ZIP_UNZIP_LIMIT is not None:
        LOGGER.info('Checking File/Folder Size...')
        if size > ZIP_UNZIP_LIMIT * 1024**3:
            msg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(size)}.'
            return sendMessage(msg, listener.bot, listener.update)
    LOGGER.info(f"Download Name: {name}")
    drive = GoogleDriveHelper(name, listener)
    gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                string.digits,
                                                k=12))
    download_status = GdDownloadStatus(drive, size, listener, gid)
    with download_dict_lock:
        download_dict[listener.uid] = download_status
    sendStatusMessage(listener.update, listener.bot)
    drive.download(link)
    if is_gdtot:
        drive.deletefile(link)
Пример #14
0
def leechSet(update, context):
    user_id = update.message.from_user.id
    path = f"Thumbnails/{user_id}.jpg"
    msg = f"Leech Type for {user_id} user is "
    if (user_id in AS_DOC_USERS
            or user_id not in AS_MEDIA_USERS and AS_DOCUMENT):
        msg += "DOCUMENT"
    else:
        msg += "MEDIA"
    msg += "\nCustom Thumbnail "
    msg += "exists" if os.path.exists(path) else "not exists"
    buttons = button_build.ButtonMaker()
    buttons.sbutton("As Document", f"doc {user_id}")
    buttons.sbutton("As Media", f"med {user_id}")
    buttons.sbutton("Delete Thumbnail", f"thumb {user_id}")
    if AUTO_DELETE_MESSAGE_DURATION == -1:
        buttons.sbutton("Close", f"closeset {user_id}")
    button = InlineKeyboardMarkup(buttons.build_menu(2))
    choose_msg = sendMarkup(msg, context.bot, update, button)
    threading.Thread(target=auto_delete_message,
                     args=(context.bot, update.message, choose_msg)).start()
Пример #15
0
    def add_download(self, message, path, filename):
        _message = self.__user_bot.get_messages(
            message.chat.id, reply_to_message_ids=message.message_id)
        media = None
        media_array = [_message.document, _message.video, _message.audio]
        for i in media_array:
            if i is not None:
                media = i
                break
        if media is not None:
            with global_lock:
                # For avoiding locking the thread lock for long time unnecessarily
                download = media.file_id not in GLOBAL_GID
            if filename == "":
                name = media.file_name
            else:
                name = filename
                path = path + name

            if download:
                if STOP_DUPLICATE and not self.__listener.isLeech:
                    LOGGER.info('Checking File/Folder if already in Drive...')
                    smsg, button = GoogleDriveHelper().drive_list(
                        name, True, True)
                    if smsg:
                        msg = "File/Folder is already available in Drive.\nHere are the search results:"
                        return sendMarkup(msg, self.__listener.bot,
                                          self.__listener.update, button)
                self.__onDownloadStart(name, media.file_size, media.file_id)
                LOGGER.info(
                    f'Downloading Telegram file with id: {media.file_id}')
                Thread(target=self.__download, args=(_message, path)).start()
            else:
                self.__onDownloadError('File already being downloaded!')
        else:
            self.__onDownloadError('No document in the replied message')
Пример #16
0
def torser(update, context):
    user_id = update.message.from_user.id
    try:
        key = update.message.text.split(" ", maxsplit=1)[1]
    except IndexError:
        return sendMessage("Send a search key along with command", context.bot, update)
    if SEARCH_API_LINK is not None and SEARCH_PLUGINS is not None:
        buttons = button_build.ButtonMaker()
        buttons.sbutton('Api', f"torser {user_id} api")
        buttons.sbutton('Plugins', f"torser {user_id} plugin")
        buttons.sbutton("Cancel", f"torser {user_id} cancel")
        button = InlineKeyboardMarkup(buttons.build_menu(2))
        sendMarkup('Choose tool to search:', context.bot, update, button)
    elif SEARCH_API_LINK is not None and SEARCH_PLUGINS is None:
        button = _api_buttons(user_id)
        sendMarkup('Choose site to search:', context.bot, update, button)
    elif SEARCH_API_LINK is None and SEARCH_PLUGINS is not None:
        button = _plugin_buttons(user_id)
        sendMarkup('Choose site to search:', context.bot, update, button)
    else:
        return sendMessage("No API link or search PLUGINS added for this function", context.bot, update)
Пример #17
0
def _qb_listener(listener, client, gid, ext_hash, select, meta_time, path):
    stalled_time = time()
    uploaded = False
    sizeChecked = False
    dupChecked = False
    rechecked = False
    get_info = 0
    while True:
        sleep(4)
        tor_info = client.torrents_info(torrent_hashes=ext_hash)
        if len(tor_info) == 0:
            with download_dict_lock:
                if listener.uid not in list(download_dict.keys()):
                    client.auth_log_out()
                    break
            get_info += 1
            if get_info > 10:
                client.auth_log_out()
                break
            continue
        get_info = 0
        try:
            tor_info = tor_info[0]
            if tor_info.state == "metaDL":
                stalled_time = time()
                if time(
                ) - meta_time >= 999999999:  # timeout while downloading metadata
                    client.torrents_pause(torrent_hashes=ext_hash)
                    sleep(0.3)
                    listener.onDownloadError("Dead Torrent!")
                    client.torrents_delete(torrent_hashes=ext_hash,
                                           delete_files=True)
                    client.auth_log_out()
                    break
            elif tor_info.state == "downloading":
                stalled_time = time()
                if STOP_DUPLICATE and not listener.isLeech and not dupChecked and ospath.isdir(
                        f'{path}'):
                    LOGGER.info('Checking File/Folder if already in Drive')
                    qbname = str(listdir(f'{path}')[-1])
                    if qbname.endswith('.!qB'):
                        qbname = ospath.splitext(qbname)[0]
                    if listener.isZip:
                        qbname = qbname + ".zip"
                    if not listener.extract:
                        qbmsg, button = GoogleDriveHelper().drive_list(
                            qbname, True)
                        if qbmsg:
                            msg = "File/Folder is already available in Drive."
                            client.torrents_pause(torrent_hashes=ext_hash)
                            sleep(0.3)
                            listener.onDownloadError(msg)
                            sendMarkup("Here are the search results:",
                                       listener.bot, listener.update, button)
                            client.torrents_delete(torrent_hashes=ext_hash,
                                                   delete_files=True)
                            client.auth_log_out()
                            break
                    dupChecked = True
                if not sizeChecked:
                    limit = None
                    if ZIP_UNZIP_LIMIT is not None and (listener.isZip
                                                        or listener.extract):
                        mssg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB'
                        limit = ZIP_UNZIP_LIMIT
                    elif TORRENT_DIRECT_LIMIT is not None:
                        mssg = f'Torrent limit is {TORRENT_DIRECT_LIMIT}GB'
                        limit = TORRENT_DIRECT_LIMIT
                    if limit is not None:
                        LOGGER.info('Checking File/Folder Size...')
                        sleep(1)
                        size = tor_info.size
                        if size > limit * 1024**3:
                            client.torrents_pause(torrent_hashes=ext_hash)
                            sleep(0.3)
                            listener.onDownloadError(
                                f"{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}"
                            )
                            client.torrents_delete(torrent_hashes=ext_hash,
                                                   delete_files=True)
                            client.auth_log_out()
                            break
                    sizeChecked = True
            elif tor_info.state == "stalledDL":
                if not rechecked and 0.99989999999999999 < tor_info.progress < 1:
                    LOGGER.info(
                        f"Force recheck - Name: {tor_info.name} Hash: {ext_hash} Downloaded Bytes: {tor_info.downloaded} Size: {tor_info.size} Total Size: {tor_info.total_size}"
                    )
                    client.torrents_recheck(torrent_hashes=ext_hash)
                    rechecked = True
                elif time(
                ) - stalled_time >= 999999999:  # timeout after downloading metadata
                    client.torrents_pause(torrent_hashes=ext_hash)
                    sleep(0.3)
                    listener.onDownloadError("Dead Torrent!")
                    client.torrents_delete(torrent_hashes=ext_hash,
                                           delete_files=True)
                    client.auth_log_out()
                    break
            elif tor_info.state == "missingFiles":
                client.torrents_recheck(torrent_hashes=ext_hash)
            elif tor_info.state == "error":
                client.torrents_pause(torrent_hashes=ext_hash)
                sleep(0.3)
                listener.onDownloadError(
                    "No enough space for this torrent on device")
                client.torrents_delete(torrent_hashes=ext_hash,
                                       delete_files=True)
                client.auth_log_out()
                break
            elif tor_info.state in [
                    "uploading", "queuedUP", "stalledUP", "forcedUP"
            ] and not uploaded:
                uploaded = True
                if not QB_SEED:
                    client.torrents_pause(torrent_hashes=ext_hash)
                if select:
                    for dirpath, subdir, files in walk(f"{path}",
                                                       topdown=False):
                        for filee in files:
                            if filee.endswith(".!qB") or filee.endswith(
                                    '.parts') and filee.startswith('.'):
                                osremove(ospath.join(dirpath, filee))
                        for folder in subdir:
                            if folder == ".unwanted":
                                rmtree(ospath.join(dirpath, folder))
                    for dirpath, subdir, files in walk(f"{path}",
                                                       topdown=False):
                        if not listdir(dirpath):
                            rmdir(dirpath)
                listener.onDownloadComplete()
                if QB_SEED:
                    with download_dict_lock:
                        if listener.uid not in list(download_dict.keys()):
                            client.torrents_delete(torrent_hashes=ext_hash,
                                                   delete_files=True)
                            client.auth_log_out()
                            break
                        download_dict[listener.uid] = QbDownloadStatus(
                            listener, client, gid, ext_hash, select)
                    update_all_messages()
                    LOGGER.info(f"Seeding started: {tor_info.name}")
                else:
                    client.torrents_delete(torrent_hashes=ext_hash,
                                           delete_files=True)
                    client.auth_log_out()
                    break
            elif tor_info.state == 'pausedUP' and QB_SEED:
                listener.onUploadError(
                    f"Seeding stopped with Ratio: {round(tor_info.ratio, 3)} and Time: {get_readable_time(tor_info.seeding_time)}"
                )
                client.torrents_delete(torrent_hashes=ext_hash,
                                       delete_files=True)
                client.auth_log_out()
                break
        except:
            pass
Пример #18
0
    def onUploadComplete(self, link: str, size, files, folders, typ):
        if self.isLeech:
            if self.isQbit and QB_SEED:
                pass
            else:
                with download_dict_lock:
                    try:
                        clean_download(download_dict[self.uid].path())
                    except FileNotFoundError:
                        pass
                    del download_dict[self.uid]
                    dcount = len(download_dict)
                if dcount == 0:
                    self.clean()
                else:
                    update_all_messages()
            count = len(files)
            msg = f'<b>Name: </b><code>{link}</code>\n\n'
            msg += f'<b>Size: </b>{get_readable_file_size(size)}\n'
            msg += f'<b>Total Files: </b>{count}'
            if typ != 0:
                msg += f'\n<b>Corrupted Files: </b>{typ}'
            if self.message.chat.type == 'private':
                sendMessage(msg, self.bot, self.update)
            else:
                chat_id = str(self.message.chat.id)[4:]
                msg += f'\n<b>cc: </b>{self.tag}\n\n'
                fmsg = ''
                for index, item in enumerate(list(files), start=1):
                    msg_id = files[item]
                    link = f"https://t.me/c/{chat_id}/{msg_id}"
                    fmsg += f"{index}. <a href='{link}'>{item}</a>\n"
                    if len(fmsg.encode('utf-8') + msg.encode('utf-8')) > 4000:
                        sleep(2)
                        sendMessage(msg + fmsg, self.bot, self.update)
                        fmsg = ''
                if fmsg != '':
                    sleep(2)
                    sendMessage(msg + fmsg, self.bot, self.update)
            return

        with download_dict_lock:
            msg = f'<b>Name: </b><code>{download_dict[self.uid].name()}</code>\n\n<b>Size: </b>{size}'
            msg += f'\n\n<b>Type: </b>{typ}'
            if ospath.isdir(f'{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}'):
                msg += f'\n<b>SubFolders: </b>{folders}'
                msg += f'\n<b>Files: </b>{files}'
            buttons = ButtonMaker()
            link = short_url(link)
            buttons.buildbutton("☁️ Drive Link", link)
            LOGGER.info(f'Done Uploading {download_dict[self.uid].name()}')
            if INDEX_URL is not None:
                url_path = requests.utils.quote(f'{download_dict[self.uid].name()}')
                share_url = f'{INDEX_URL}/{url_path}'
                if ospath.isdir(f'{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}'):
                    share_url += '/'
                    share_url = short_url(share_url)
                    buttons.buildbutton("⚡ Index Link", share_url)
                else:
                    share_url = short_url(share_url)
                    buttons.buildbutton("⚡ Index Link", share_url)
                    if VIEW_LINK:
                        share_urls = f'{INDEX_URL}/{url_path}?a=view'
                        share_urls = short_url(share_urls)
                        buttons.buildbutton("🌐 View Link", share_urls)
            if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:
                buttons.buildbutton(f"{BUTTON_FOUR_NAME}", f"{BUTTON_FOUR_URL}")
            if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:
                buttons.buildbutton(f"{BUTTON_FIVE_NAME}", f"{BUTTON_FIVE_URL}")
            if BUTTON_SIX_NAME is not None and BUTTON_SIX_URL is not None:
                buttons.buildbutton(f"{BUTTON_SIX_NAME}", f"{BUTTON_SIX_URL}")
        msg += f'\n\n<b>cc: </b>{self.tag}'
        if self.isQbit and QB_SEED:
           return sendMarkup(msg, self.bot, self.update, InlineKeyboardMarkup(buttons.build_menu(2)))
        else:
            with download_dict_lock:
                try:
                    clean_download(download_dict[self.uid].path())
                except FileNotFoundError:
                    pass
                del download_dict[self.uid]
                count = len(download_dict)
            sendMarkup(msg, self.bot, self.update, InlineKeyboardMarkup(buttons.build_menu(2)))
            if count == 0:
                self.clean()
            else:
                update_all_messages()
Пример #19
0
def cloneNode(update, context):
    args = update.message.text.split(" ", maxsplit=1)
    reply_to = update.message.reply_to_message
    if len(args) > 1:
        link = args[1]
        if update.message.from_user.username:
            tag = f"@{update.message.from_user.username}"
        else:
            tag = update.message.from_user.mention_html(
                update.message.from_user.first_name)
    elif reply_to is not None:
        link = reply_to.text
        if reply_to.from_user.username:
            tag = f"@{reply_to.from_user.username}"
        else:
            tag = reply_to.from_user.mention_html(
                reply_to.from_user.first_name)
    else:
        link = ''
    gdtot_link = is_gdtot_link(link)
    if gdtot_link:
        try:
            msg = sendMessage(f"Processing: <code>{link}</code>", context.bot,
                              update)
            link = gdtot(link)
            deleteMessage(context.bot, msg)
        except DirectDownloadLinkException as e:
            deleteMessage(context.bot, msg)
            return sendMessage(str(e), context.bot, update)
    if is_gdrive_link(link):
        gd = GoogleDriveHelper()
        res, size, name, files = gd.helper(link)
        if res != "":
            return sendMessage(res, context.bot, update)
        if STOP_DUPLICATE:
            LOGGER.info('Checking File/Folder if already in Drive...')
            smsg, button = gd.drive_list(name, True, True)
            if smsg:
                msg3 = "File/Folder is already available in Drive.\nHere are the search results:"
                sendMarkup(msg3, context.bot, update, button)
                if gdtot_link:
                    gd.deletefile(link)
                return
        if CLONE_LIMIT is not None:
            LOGGER.info('Checking File/Folder Size...')
            if size > CLONE_LIMIT * 1024**3:
                msg2 = f'Failed, Clone limit is {CLONE_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(size)}.'
                return sendMessage(msg2, context.bot, update)
        if files <= 10:
            msg = sendMessage(f"Cloning: <code>{link}</code>", context.bot,
                              update)
            result, button = gd.clone(link)
            deleteMessage(context.bot, msg)
        else:
            drive = GoogleDriveHelper(name)
            gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                        string.digits,
                                                        k=12))
            clone_status = CloneStatus(drive, size, update, gid)
            with download_dict_lock:
                download_dict[update.message.message_id] = clone_status
            sendStatusMessage(update, context.bot)
            result, button = drive.clone(link)
            with download_dict_lock:
                del download_dict[update.message.message_id]
                count = len(download_dict)
            try:
                if count == 0:
                    Interval[0].cancel()
                    del Interval[0]
                    delete_all_messages()
                else:
                    update_all_messages()
            except IndexError:
                pass
        cc = f'\n\n<b>cc: </b>{tag}'
        if button in ["cancelled", ""]:
            sendMessage(f"{tag} {result}", context.bot, update)
        else:
            sendMarkup(result + cc, context.bot, update, button)
        if gdtot_link:
            gd.deletefile(link)
    else:
        sendMessage(
            'Send Gdrive or gdtot link along with command or by replying to the link by command',
            context.bot, update)
Пример #20
0
def _qb_listener(listener, client, ext_hash, select, path):
    stalled_time = time()
    uploaded = False
    sizeChecked = False
    dupChecked = False
    rechecked = False
    while True:
        sleep(4)
        try:
            tor_info = client.torrents_info(torrent_hashes=ext_hash)
            if len(tor_info) == 0:
                with download_dict_lock:
                    if listener.uid not in list(download_dict.keys()):
                        client.auth_log_out()
                        break
                continue
            tor_info = tor_info[0]
            if tor_info.state == "metaDL":
                stalled_time = time()
                if QB_TIMEOUT is not None and time(
                ) - tor_info.added_on >= QB_TIMEOUT:  #timeout while downloading metadata
                    _onDownloadError("Dead Torrent!", client, ext_hash,
                                     listener)
                    break
            elif tor_info.state == "downloading":
                stalled_time = time()
                if STOP_DUPLICATE and not dupChecked and ospath.isdir(
                        f'{path}') and not listener.isLeech:
                    LOGGER.info('Checking File/Folder if already in Drive')
                    qbname = str(listdir(f'{path}')[-1])
                    if qbname.endswith('.!qB'):
                        qbname = ospath.splitext(qbname)[0]
                    if listener.isZip:
                        qbname = qbname + ".zip"
                    elif listener.extract:
                        try:
                            qbname = get_base_name(qbname)
                        except:
                            qbname = None
                    if qbname is not None:
                        qbmsg, button = GoogleDriveHelper().drive_list(
                            qbname, True)
                        if qbmsg:
                            msg = "File/Folder is already available in Drive."
                            _onDownloadError(msg, client, ext_hash, listener)
                            sendMarkup("Here are the search results:",
                                       listener.bot, listener.update, button)
                            break
                    dupChecked = True
                if not sizeChecked:
                    sleep(1)
                    size = tor_info.size
                    arch = any([listener.isZip, listener.extract])
                    if STORAGE_THRESHOLD is not None:
                        acpt = check_storage_threshold(size, arch)
                        if not acpt:
                            msg = f'You must leave {STORAGE_THRESHOLD}GB free storage.'
                            msg += f'\nYour File/Folder size is {get_readable_file_size(size)}'
                            _onDownloadError(msg, client, ext_hash, listener)
                            break
                    limit = None
                    if ZIP_UNZIP_LIMIT is not None and arch:
                        mssg = f'Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB'
                        limit = ZIP_UNZIP_LIMIT
                    elif TORRENT_DIRECT_LIMIT is not None:
                        mssg = f'Torrent limit is {TORRENT_DIRECT_LIMIT}GB'
                        limit = TORRENT_DIRECT_LIMIT
                    if limit is not None:
                        LOGGER.info('Checking File/Folder Size...')
                        if size > limit * 1024**3:
                            fmsg = f"{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}"
                            _onDownloadError(fmsg, client, ext_hash, listener)
                            break
                    sizeChecked = True
            elif tor_info.state == "stalledDL":
                if not rechecked and 0.99989999999999999 < tor_info.progress < 1:
                    msg = f"Force recheck - Name: {tor_info.name} Hash: "
                    msg += f"{ext_hash} Downloaded Bytes: {tor_info.downloaded} "
                    msg += f"Size: {tor_info.size} Total Size: {tor_info.total_size}"
                    LOGGER.info(msg)
                    client.torrents_recheck(torrent_hashes=ext_hash)
                    rechecked = True
                elif QB_TIMEOUT is not None and time(
                ) - stalled_time >= QB_TIMEOUT:  # timeout after downloading metadata
                    _onDownloadError("Dead Torrent!", client, ext_hash,
                                     listener)
                    break
            elif tor_info.state == "missingFiles":
                client.torrents_recheck(torrent_hashes=ext_hash)
            elif tor_info.state == "error":
                _onDownloadError("No enough space for this torrent on device",
                                 client, ext_hash, listener)
                break
            elif (tor_info.state.lower().endswith("up")
                  or tor_info.state == "uploading") and not uploaded:
                LOGGER.info(f"onQbDownloadComplete: {ext_hash}")
                uploaded = True
                if not QB_SEED:
                    client.torrents_pause(torrent_hashes=ext_hash)
                if select:
                    clean_unwanted(path)
                listener.onDownloadComplete()
                if QB_SEED and not listener.isLeech and not listener.extract:
                    with download_dict_lock:
                        if listener.uid not in list(download_dict.keys()):
                            client.torrents_delete(torrent_hashes=ext_hash,
                                                   delete_files=True)
                            client.auth_log_out()
                            break
                        download_dict[listener.uid] = QbDownloadStatus(
                            listener, client, ext_hash, select)
                    update_all_messages()
                    LOGGER.info(f"Seeding started: {tor_info.name}")
                else:
                    client.torrents_delete(torrent_hashes=ext_hash,
                                           delete_files=True)
                    client.auth_log_out()
                    break
            elif tor_info.state == 'pausedUP' and QB_SEED:
                listener.onUploadError(
                    f"Seeding stopped with Ratio: {round(tor_info.ratio, 3)} and Time: {get_readable_time(tor_info.seeding_time)}"
                )
                client.torrents_delete(torrent_hashes=ext_hash,
                                       delete_files=True)
                client.auth_log_out()
                update_all_messages()
                break
        except Exception as e:
            LOGGER.error(str(e))
Пример #21
0
def leechSet(update, context):
    msg, button = getleechinfo(update.message.from_user)
    choose_msg = sendMarkup(msg, context.bot, update, button)
    Thread(target=auto_delete_message,
           args=(context.bot, update.message, choose_msg)).start()
Пример #22
0
def add_qb_torrent(link, path, listener, select):
    client = get_client()
    pincode = ""
    try:
        if ospath.exists(link):
            is_file = True
            ext_hash = _get_hash_file(link)
        else:
            is_file = False
            ext_hash = _get_hash_magnet(link)
        tor_info = client.torrents_info(torrent_hashes=ext_hash)
        if len(tor_info) > 0:
            sendMessage("This Torrent is already in list.", listener.bot,
                        listener.update)
            client.auth_log_out()
            return
        if is_file:
            op = client.torrents_add(torrent_files=[link], save_path=path)
            osremove(link)
        else:
            op = client.torrents_add(link, save_path=path)
        sleep(0.3)
        if op.lower() == "ok.":
            meta_time = time()
            tor_info = client.torrents_info(torrent_hashes=ext_hash)
            if len(tor_info) == 0:
                while True:
                    if time() - meta_time >= 30:
                        ermsg = "The Torrent was not added. Report when you see this error"
                        sendMessage(ermsg, listener.bot, listener.update)
                        client.torrents_delete(torrent_hashes=ext_hash,
                                               delete_files=True)
                        client.auth_log_out()
                        return
                    tor_info = client.torrents_info(torrent_hashes=ext_hash)
                    if len(tor_info) > 0:
                        break
        else:
            sendMessage("This is an unsupported/invalid link.", listener.bot,
                        listener.update)
            client.torrents_delete(torrent_hashes=ext_hash, delete_files=True)
            client.auth_log_out()
            return
        tor_info = tor_info[0]
        ext_hash = tor_info.hash
        gid = ''.join(random.SystemRandom().choices(string.ascii_letters +
                                                    string.digits,
                                                    k=14))
        with download_dict_lock:
            download_dict[listener.uid] = QbDownloadStatus(
                listener, client, gid, ext_hash, select)
        LOGGER.info(
            f"QbitDownload started: {tor_info.name} - Hash: {ext_hash}")
        Thread(target=_qb_listener,
               args=(listener, client, gid, ext_hash, select, meta_time,
                     path)).start()
        if BASE_URL is not None and select:
            if not is_file:
                metamsg = "Downloading Metadata, wait then you can select files or mirror torrent file"
                meta = sendMessage(metamsg, listener.bot, listener.update)
                while True:
                    tor_info = client.torrents_info(torrent_hashes=ext_hash)
                    if len(tor_info) == 0:
                        deleteMessage(listener.bot, meta)
                        return
                    try:
                        tor_info = tor_info[0]
                        if tor_info.state in ["metaDL", "checkingResumeData"]:
                            sleep(1)
                        else:
                            deleteMessage(listener.bot, meta)
                            break
                    except:
                        deleteMessage(listener.bot, meta)
                        return
            sleep(0.5)
            client.torrents_pause(torrent_hashes=ext_hash)
            for n in str(ext_hash):
                if n.isdigit():
                    pincode += str(n)
                if len(pincode) == 4:
                    break
            buttons = button_build.ButtonMaker()
            if WEB_PINCODE:
                buttons.buildbutton("Select Files",
                                    f"{BASE_URL}/app/files/{ext_hash}")
                buttons.sbutton("Pincode", f"pin {gid} {pincode}")
            else:
                buttons.buildbutton(
                    "Select Files",
                    f"{BASE_URL}/app/files/{ext_hash}?pin_code={pincode}")
            buttons.sbutton("Done Selecting", f"done {gid} {ext_hash}")
            QBBUTTONS = InlineKeyboardMarkup(buttons.build_menu(2))
            msg = "Your download paused. Choose files then press Done Selecting button to start downloading."
            sendMarkup(msg, listener.bot, listener.update, QBBUTTONS)
        else:
            sendStatusMessage(listener.update, listener.bot)
    except Exception as e:
        sendMessage(str(e), listener.bot, listener.update)
        client.auth_log_out()
Пример #23
0
def _watch(bot, update, isZip=False, isLeech=False, pswd=None, tag=None):
    mssg = update.message.text
    message_args = mssg.split(' ')
    name_args = mssg.split('|', maxsplit=1)
    user_id = update.message.from_user.id
    msg_id = update.message.message_id

    try:
        link = message_args[1].strip()
        if link.startswith("|") or link.startswith("pswd: "):
            link = ''
    except IndexError:
        link = ''

    try:
        name = name_args[1]
        name = name.split(' pswd: ')[0]
        name = name.strip()
    except IndexError:
        name = ''

    pswdMsg = mssg.split(' pswd: ')
    if len(pswdMsg) > 1:
        pswd = pswdMsg[1]

    if update.message.from_user.username:
        tag = f"@{update.message.from_user.username}"
    else:
        tag = update.message.from_user.mention_html(update.message.from_user.first_name)

    reply_to = update.message.reply_to_message
    if reply_to is not None:
        link = reply_to.text.strip()
        if reply_to.from_user.username:
            tag = f"@{reply_to.from_user.username}"
        else:
            tag = reply_to.from_user.mention_html(reply_to.from_user.first_name)

    if not is_url(link):
        help_msg = "<b>Send link along with command line:</b>"
        help_msg += "\n<code>/command</code> {link} |newname pswd: mypassword [𝚣𝚒𝚙]"
        help_msg += "\n\n<b>By replying to link:</b>"
        help_msg += "\n<code>/command</code> |newname pswd: mypassword [𝚣𝚒𝚙]"
        return sendMessage(help_msg, bot, update)

    LOGGER.info(link)
    listener = MirrorListener(bot, update, isZip, isLeech=isLeech, pswd=pswd, tag=tag)
    buttons = button_build.ButtonMaker()
    best_video = "bv*+ba/b"
    best_audio = "ba/b"
    ydl = YoutubeDLHelper(listener)
    try:
        result = ydl.extractMetaData(link, name, True)
    except Exception as e:
        return sendMessage(str(e), bot, update)
    if 'entries' in result:
        for i in ['144', '240', '360', '480', '720', '1080', '1440', '2160']:
            video_format = f"bv*[height<={i}][ext=mp4]+ba/b"
            buttons.sbutton(f"{i}-mp4", f"qu {msg_id} {video_format} t")
            video_format = f"bv*[height<={i}][ext=webm]+ba/b"
            buttons.sbutton(f"{i}-webm", f"qu {msg_id} {video_format} t")
        buttons.sbutton("Audios", f"qu {msg_id} audio t")
        buttons.sbutton("Best Videos", f"qu {msg_id} {best_video} t")
        buttons.sbutton("Best Audios", f"qu {msg_id} {best_audio} t")
        buttons.sbutton("Cancel", f"qu {msg_id} cancel")
        YTBUTTONS = InlineKeyboardMarkup(buttons.build_menu(3))
        listener_dict[msg_id] = [listener, user_id, link, name, YTBUTTONS]
        bmsg = sendMarkup('Choose Playlist Videos Quality:', bot, update, YTBUTTONS)
    else:
        formats = result.get('formats')
        formats_dict = {}
        if formats is not None:
            for frmt in formats:
                if not frmt.get('tbr') or not frmt.get('height'):
                    continue

                if frmt.get('fps'):
                    quality = f"{frmt['height']}p{frmt['fps']}-{frmt['ext']}"
                else:
                    quality = f"{frmt['height']}p-{frmt['ext']}"

                if frmt.get('filesize'):
                    size = frmt['filesize']
                elif frmt.get('filesize_approx'):
                    size = frmt['filesize_approx']
                else:
                    size = 0

                if quality in formats_dict:
                    formats_dict[quality][frmt['tbr']] = size
                else:
                    subformat = {}
                    subformat[frmt['tbr']] = size
                    formats_dict[quality] = subformat

            for forDict in formats_dict:
                if len(formats_dict[forDict]) == 1:
                    qual_fps_ext = resplit(r'p|-', forDict, maxsplit=2)
                    height = qual_fps_ext[0]
                    fps = qual_fps_ext[1]
                    ext = qual_fps_ext[2]
                    if fps != '':
                        video_format = f"bv*[height={height}][fps={fps}][ext={ext}]+ba/b"
                    else:
                        video_format = f"bv*[height={height}][ext={ext}]+ba/b"
                    size = list(formats_dict[forDict].values())[0]
                    buttonName = f"{forDict} ({get_readable_file_size(size)})"
                    buttons.sbutton(str(buttonName), f"qu {msg_id} {video_format}")
                else:
                    buttons.sbutton(str(forDict), f"qu {msg_id} dict {forDict}")
        buttons.sbutton("Audios", f"qu {msg_id} audio")
        buttons.sbutton("Best Video", f"qu {msg_id} {best_video}")
        buttons.sbutton("Best Audio", f"qu {msg_id} {best_audio}")
        buttons.sbutton("Cancel", f"qu {msg_id} cancel")
        YTBUTTONS = InlineKeyboardMarkup(buttons.build_menu(2))
        listener_dict[msg_id] = [listener, user_id, link, name, YTBUTTONS, formats_dict]
        bmsg = sendMarkup('Choose Video Quality:', bot, update, YTBUTTONS)

    Thread(target=_auto_cancel, args=(bmsg, msg_id)).start()
Пример #24
0
def _watch(bot, update, isZip=False, isLeech=False):
    mssg = update.message.text
    user_id = update.message.from_user.id
    msg_id = update.message.message_id

    try:
        link = mssg.split(' ')[1].strip()
        if link.startswith(("|", "pswd:", "args:")):
            link = ''
    except IndexError:
        link = ''
    try:
        name_arg = mssg.split('|', maxsplit=1)
        if 'args: ' in name_arg[0]:
            raise IndexError
        else:
            name = name_arg[1]
        name = resplit(r' pswd: | args: ', name)[0]
        name = name.strip()
    except IndexError:
        name = ''
    try:
        pswd = mssg.split(' pswd: ')[1]
        pswd = pswd.split(' args: ')[0]
    except IndexError:
        pswd = None

    try:
        args = mssg.split(' args: ')[1]
    except IndexError:
        args = None

    if update.message.from_user.username:
        tag = f"@{update.message.from_user.username}"
    else:
        tag = update.message.from_user.mention_html(
            update.message.from_user.first_name)

    reply_to = update.message.reply_to_message
    if reply_to is not None:
        if len(link) == 0:
            link = reply_to.text.strip()
        if reply_to.from_user.username:
            tag = f"@{reply_to.from_user.username}"
        else:
            tag = reply_to.from_user.mention_html(
                reply_to.from_user.first_name)

    if not is_url(link):
        help_msg = "<b>Send link along with command line:</b>"
        help_msg += "\n<code>/command</code> {link} |newname pswd: mypassword [𝚣𝚒𝚙] args: x:y|x1:y1"
        help_msg += "\n\n<b>By replying to link:</b>"
        help_msg += "\n<code>/command</code> |newname pswd: mypassword [𝚣𝚒𝚙] args: x:y|x1:y1"
        help_msg += "\n\n<b>Args Example:</b> args: playliststart:^10|match_filter:season_number=18|matchtitle:S1"
        help_msg += "\n\n<b>NOTE:</b> Add `^` before integer, some values must be integer and some string."
        help_msg += " Like playlist_items:10 works with string so no need to add `^` before the number"
        help_msg += " but playlistend works only with integer so you must add `^` before the number like example above."
        help_msg += "\n\nCheck all arguments from this <a href='https://github.com/yt-dlp/yt-dlp/blob/a3125791c7a5cdf2c8c025b99788bf686edd1a8a/yt_dlp/YoutubeDL.py#L194'>FILE</a>."
        return sendMessage(help_msg, bot, update)

    listener = MirrorListener(bot,
                              update,
                              isZip,
                              isLeech=isLeech,
                              pswd=pswd,
                              tag=tag)
    buttons = button_build.ButtonMaker()
    best_video = "bv*+ba/b"
    best_audio = "ba/b"
    ydl = YoutubeDLHelper(listener)
    try:
        result = ydl.extractMetaData(link, name, True)
    except Exception as e:
        msg = str(e).replace('<', ' ').replace('>', ' ')
        return sendMessage(tag + " " + msg, bot, update)
    if 'entries' in result:
        for i in ['144', '240', '360', '480', '720', '1080', '1440', '2160']:
            video_format = f"bv*[height<={i}][ext=mp4]"
            buttons.sbutton(f"{i}-mp4", f"qu {msg_id} {video_format} t")
            video_format = f"bv*[height<={i}][ext=webm]"
            buttons.sbutton(f"{i}-webm", f"qu {msg_id} {video_format} t")
        buttons.sbutton("Audios", f"qu {msg_id} audio t")
        buttons.sbutton("Best Videos", f"qu {msg_id} {best_video} t")
        buttons.sbutton("Best Audios", f"qu {msg_id} {best_audio} t")
        buttons.sbutton("Cancel", f"qu {msg_id} cancel")
        YTBUTTONS = InlineKeyboardMarkup(buttons.build_menu(3))
        listener_dict[msg_id] = [
            listener, user_id, link, name, YTBUTTONS, args
        ]
        bmsg = sendMarkup('Choose Playlist Videos Quality:', bot, update,
                          YTBUTTONS)
    else:
        formats = result.get('formats')
        formats_dict = {}
        if formats is not None:
            for frmt in formats:
                if not frmt.get('tbr') or not frmt.get('height'):
                    continue

                if frmt.get('fps'):
                    quality = f"{frmt['height']}p{frmt['fps']}-{frmt['ext']}"
                else:
                    quality = f"{frmt['height']}p-{frmt['ext']}"

                if frmt.get('filesize'):
                    size = frmt['filesize']
                elif frmt.get('filesize_approx'):
                    size = frmt['filesize_approx']
                else:
                    size = 0

                if quality in formats_dict:
                    formats_dict[quality][frmt['tbr']] = size
                else:
                    subformat = {}
                    subformat[frmt['tbr']] = size
                    formats_dict[quality] = subformat

            for forDict in formats_dict:
                if len(formats_dict[forDict]) == 1:
                    qual_fps_ext = resplit(r'p|-', forDict, maxsplit=2)
                    height = qual_fps_ext[0]
                    fps = qual_fps_ext[1]
                    ext = qual_fps_ext[2]
                    if fps != '':
                        video_format = f"bv*[height={height}][fps={fps}][ext={ext}]"
                    else:
                        video_format = f"bv*[height={height}][ext={ext}]"
                    size = list(formats_dict[forDict].values())[0]
                    buttonName = f"{forDict} ({get_readable_file_size(size)})"
                    buttons.sbutton(str(buttonName),
                                    f"qu {msg_id} {video_format}")
                else:
                    buttons.sbutton(str(forDict),
                                    f"qu {msg_id} dict {forDict}")
        buttons.sbutton("Audios", f"qu {msg_id} audio")
        buttons.sbutton("Best Video", f"qu {msg_id} {best_video}")
        buttons.sbutton("Best Audio", f"qu {msg_id} {best_audio}")
        buttons.sbutton("Cancel", f"qu {msg_id} cancel")
        YTBUTTONS = InlineKeyboardMarkup(buttons.build_menu(2))
        listener_dict[msg_id] = [
            listener, user_id, link, name, YTBUTTONS, args, formats_dict
        ]
        bmsg = sendMarkup('Choose Video Quality:', bot, update, YTBUTTONS)

    Thread(target=_auto_cancel, args=(bmsg, msg_id)).start()