Exemplo n.º 1
0
def onedrive(update, context):

    bot = context.bot
    message_args = update.message.text.split(' ')
    try:
        link = message_args[1]
    except IndexError:
        link = ''
    LOGGER.info(link)
    link = link.strip()
    tag = None
    if not bot_utils.is_url(link):
        sendMessage('No download source provided', bot, update)
        return

    root = unquote(link).rsplit("/", 1)[1].encode(errors='ignore').decode()
    if root == "":
        sendMessage('Root Error', bot, update)
        return
    links = get_onedrive_dl_links(link)

    listener = MirrorListener(bot, update, False, tag, root=root)
    ariaDlManager.add_download(f'{DOWNLOAD_DIR}/{listener.uid}/{root}/', links,
                               listener)
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            bot_utils.setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                                  update_all_messages))
Exemplo n.º 2
0
def _watch(bot: Bot, update: Update, args: list, isTar=False):
    try:
        link = args[0]
    except IndexError:
        msg = f"/{BotCommands.WatchCommand} [yt_dl supported link] [quality] to mirror with youtube_dl.\n\n"
        msg += "Example of quality :- audio, 144, 360, 720, 1080.\nNote :- Quality is optional"
        sendMessage(msg, bot, update)
        return
    try:
        qual = args[1]
        if qual != "audio":
            qual = f'best[height<={qual}]/bestvideo[height<={qual}]+bestaudio'
    except IndexError:
        qual = "best/bestvideo+bestaudio"
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None

    listener = MirrorListener(bot, update, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}',
                           qual)).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 3
0
def _watch(bot: Bot, update: Update, args: list, isTar=False):
    try:
        link = args[0]
    except IndexError:
        sendMessage(f'/{BotCommands.WatchCommand} [yt_dl supported link] to mirror with youtube_dl', bot, update)
        return
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None

    listener = MirrorListener(bot, update, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(
        target=ydl.add_download,args=(
            link,
            os.path.join(
                DOWNLOAD_DIR,
                str(listener.uid)
            )
        )
    ).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 4
0
def _watch(bot: Bot, update: Update, args: list, isTar=False):
    if update.message.from_user.last_name:
        last_name = f" {update.message.from_user.last_name}"
    else:
        last_name = ""
    if update.message.from_user.username:
        username = f"- @{update.message.from_user.username}"
    else:
        username = "******"
    name = f'<a href="tg://user?id={update.message.from_user.id}">{update.message.from_user.first_name}{last_name}</a>'

    try:
        link = args[0]
    except IndexError:
        sendMessage(
            f'/{BotCommands.WatchCommand} [yt_dl supported link] to mirror with youtube_dl',
            bot, update)
        return
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None

    listener = MirrorListener(bot, update, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}')).start()
    msg = f"User: {name} {username} (<code>{update.message.from_user.id}</code>)\n" \
          f"Message: {update.message.text}"
    sendMessage(msg, bot, update)
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 5
0
def _watch(bot: Bot, update: Update, args: list, isTar=False):
    try:
        link = args[0]
    except IndexError:
        msg = f"<b>/{BotCommands.WatchCommand} or /{BotCommands.TarWatchCommand}  [ʏᴛ_ᴅʟ sᴜᴘᴘᴏʀᴛᴇᴅ ʟɪɴᴋ] ⛽ᴛᴏ ᴍɪʀʀᴏʀ ᴡɪᴛʜ Yᴏᴜʀ ʏᴏᴜᴛᴜʙᴇ_ᴅʟ</b>.\n\n"
        msg += "<b>Exᴀᴍᴘʟᴇ Oꜰ Qᴜᴀʟɪᴛʏ :- Aᴜᴅɪᴏ, 144, 360, 720, 1080.\ɴNᴏᴛᴇ :- Qᴜᴀʟɪᴛʏ Is Oᴘᴛɪᴏɴᴀʟ</b>"
        sendMessage(msg, bot, update)
        return
    try:
        qual = args[1]
        if qual != "audio":
            qual = f'bestvideo[height<={qual}]+bestaudio/best[height<={qual}]'
    except IndexError:
        qual = "bestvideo+bestaudio/best"
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None

    listener = MirrorListener(bot, update, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}',
                           qual)).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 6
0
def _watch(bot: Bot, update: Update, args: list, isTar=False):
    try:
        link = args[0]
    except IndexError:
        msg = f"/{BotCommands.WatchCommand} (link yt) (kualitas) perintah biar bot nge mirror dari link yy.\n\n"
        msg += "Contoh Kualitas : 144,240,360,480,720,1080,2160p sama audio.\nNote :- Kualitas cuma tambahan doang"
        sendMessage(msg, bot, update)
        return
    try:
        qual = args[1]
        if qual != "audio":
            qual = f'bestvideo[height<={qual}]+bestaudio/best[height<={qual}]'
    except IndexError:
        qual = "bestvideo+bestaudio/best"
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None

    listener = MirrorListener(bot, update, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}',
                           qual)).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 7
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))
def xdcc_download(update, context):

    bot = context.bot
    message_args = update.message.text.split(' ', 2)
    try:
        server_channel = message_args[1]
    except IndexError:
        server_channel = ''
    server_channel = server_channel.strip()
    if not server_channel:
        sendMessage('You need to provide a channel to join.', bot, update)
        return

    try:
        command = message_args[2]
    except IndexError:
        command = message_args[2]

    if not command:
        sendMessage('You need to provide download command.', bot, update)
        return

    server_channel = server_channel.split(",")
    server_info = {}
    args = {}

    for each_info in server_channel:
        info = each_info.split("=")
        if info[0].lower() == "channel":
            args.update({info[0]: info[1]})
        else:
            server_info.update({info[0]: info[1]})
    tag = None

    pattern = r".* (.*?) xdcc (send|batch) (.*)"
    commands = re.match(pattern, command)
    args.update({
        "bot": commands.group(1),
        "action": commands.group(2),
        "packs": commands.group(3)
    })

    gid = format(binascii.crc32((args['bot'] + args['packs']).encode('utf8')),
                 '08x')
    if getDownloadByGid(gid):
        sendMessage('Mirror already in queue.', bot, update)
        return

    root = f"/{args['bot']} {args['packs']}/"
    listener = MirrorListener(bot, update, False, tag, root=root)
    xdcc_dl = XDCCDownload(listener)
    xdcc_dl.add_download(args, f'{DOWNLOAD_DIR}{listener.uid}/{root}')
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 9
0
 def __onDownloadStart(self, name, size, file_id):
     with global_lock:
         GLOBAL_GID.add(file_id)
     with self.__resource_lock:
         self.name = name
         self.size = size
         self.__gid = file_id
     with download_dict_lock:
         download_dict[self.__listener.uid] = TelegramDownloadStatus(
             self, self.__listener, file_id)
     sendStatusMessage(self.__listener.update, self.__listener.bot)
Exemplo n.º 10
0
def add_aria2c_download(link: str, path, listener, filename):
    if is_magnet(link):
        download = aria2.add_magnet(link, {'dir': path, 'out': filename})
    else:
        download = aria2.add_uris([link], {'dir': path, 'out': filename})
    if download.error_message:
        error = str(download.error_message).replace('<', ' ').replace('>', ' ')
        LOGGER.info(f"Download Error: {error}")
        return sendMessage(error, listener.bot, listener.update)
    with download_dict_lock:
        download_dict[listener.uid] = AriaDownloadStatus(
            download.gid, listener)
        LOGGER.info(f"Started: {download.gid} DIR: {download.dir} ")
    sendStatusMessage(listener.update, listener.bot)
Exemplo n.º 11
0
def mirror_status(update, context):
    message = get_readable_message()
    if len(message) == 0:
        message = "No active downloads"
        reply_message = sendMessage(message, context.bot, update)
        threading.Thread(target=auto_delete_message,
                         args=(bot, update.message, reply_message)).start()
        return
    index = update.effective_chat.id
    with status_reply_dict_lock:
        if index in status_reply_dict.keys():
            deleteMessage(bot, status_reply_dict[index])
            del status_reply_dict[index]
    sendStatusMessage(update, context.bot)
    deleteMessage(context.bot, update.message)
Exemplo n.º 12
0
def _watch(bot: Bot, update, isTar=False, isZip=False, isLeech=False):
    mssg = update.message.text
    message_args = mssg.split(' ')
    name_args = mssg.split('|')

    try:
        link = message_args[1]
    except IndexError:
        msg = f"/{BotCommands.WatchCommand} [youtube-dl supported link] [quality] |[CustomName] to mirror with youtube-dl.\n\n"
        msg += "<b>Note: Quality and custom name are optional</b>\n\nExample of quality: audio, 144, 240, 360, 480, 720, 1080, 2160."
        msg += "\n\nIf you want to use custom filename, enter it after |"
        msg += f"\n\nExample:\n<code>/{BotCommands.WatchCommand} https://youtu.be/Pk_TthHfLeE 720 |Slam</code>\n\n"
        msg += "This file will be downloaded in 720p quality and it's name will be <b>Slam</b>"
        sendMessage(msg, bot, update)
        return

    try:
        if "|" in mssg:
            mssg = mssg.split("|")
            qual = mssg[0].split(" ")[2]
            if qual == "":
                raise IndexError
        else:
            qual = message_args[2]
        if qual != "audio":
            qual = f'bestvideo[height<={qual}]+bestaudio/best[height<={qual}]'
    except IndexError:
        qual = "bestvideo+bestaudio/best"

    try:
        name = name_args[1]
    except IndexError:
        name = ""

    pswd = ""
    listener = MirrorListener(bot,
                              update,
                              pswd,
                              isTar,
                              isZip=isZip,
                              isLeech=isLeech)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}', qual,
                           name)).start()
    sendStatusMessage(update, bot)
Exemplo n.º 13
0
def _watch(bot: Bot, update, isTar=False):
    mssg = update.message.text
    message_args = mssg.split(" ")
    name_args = mssg.split("|")
    try:
        link = message_args[1]
    except IndexError:
        msg = f"/{BotCommands.WatchCommand} [yt_dl supported link] [quality] |[CustomName] to mirror with youtube_dl.\n\n"
        msg += "<b>Note :- Quality and custom name are optional</b>\n\nExample of quality :- audio, 144, 240, 360, 480, 720, 1080, 2160."
        msg += "\n\nIf you want to use custom filename, plz enter it after |"
        msg += f"\n\nExample :-\n<code>/{BotCommands.WatchCommand} https://youtu.be/ocX2FN1nguA 720 |My video bro</code>\n\n"
        msg += "This file will be downloaded in 720p quality and it's name will be <b>My video bro</b>"
        sendMessage(msg, bot, update)
        return
    try:
        if "|" in mssg:
            mssg = mssg.split("|")
            qual = mssg[0].split(" ")[2]
            if qual == "":
                raise IndexError
        else:
            qual = message_args[2]
        if qual != "audio":
            qual = f"bestvideo[height<={qual}]+bestaudio/best[height<={qual}]"
    except IndexError:
        qual = "bestvideo+bestaudio/best"
    try:
        name = name_args[1]
    except IndexError:
        name = ""
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None
    pswd = ""
    listener = MirrorListener(bot, update, pswd, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(
        target=ydl.add_download,
        args=(link, f"{DOWNLOAD_DIR}{listener.uid}", qual, name),
    ).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
    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')
Exemplo n.º 15
0
def _watch(bot: Bot, update, isTar=False):
    mssg = update.message.text
    message_args = mssg.split(' ')
    name_args = mssg.split('|')
    try:
        link = message_args[1]
    except IndexError:
        msg = f"/{BotCommands.WatchCommand} [Bisa pake link youtube] [Kualitas] |[Kustomnama] Biar di mirror in pake link youtube.\n\n"
        msg += "<b>Note :- Kualitas dan kustom nama itu pelengkap aja ya</b>\n\nMisalkan aja :- audio, 144, 240, 360, 480, 720, 1080, 2160."
        msg += "\n\nKalo pengen pake Nama kustom bisa dipake sehabis |"
        msg += f"\n\nExample :-\n<code>/{BotCommands.WatchCommand} https://youtu.be/ocX2FN1nguA 720 |Ini videoku</code>\n\n"
        msg += "File yanh kamu minta bakalan diupload dengan kualitas 720p dengan nama<b>Ini videoku</b>"
        sendMessage(msg, bot, update)
        return
    try:
        if "|" in mssg:
            mssg = mssg.split("|")
            qual = mssg[0].split(" ")[2]
            if qual == "":
                raise IndexError
        else:
            qual = message_args[2]
        if qual != "audio":
            qual = f'bestvideo[height<={qual}]+bestaudio/best[height<={qual}]'
    except IndexError:
        qual = "bestvideo+bestaudio/best"
    try:
        name = name_args[1]
    except IndexError:
        name = ""
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None
    pswd = ""
    listener = MirrorListener(bot, update, pswd, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}', qual,
                           name)).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 16
0
def _watch(bot: Bot, update, isTar=False):
    mssg = update.message.text
    message_args = mssg.split(' ')
    name_args = mssg.split('|')
    try:
        link = message_args[1]
    except IndexError:
        msg = f"/{BotCommands.WatchCommand} [yt_dl supported link] [quality] |[CustomName] tải nhanh với youtube_dl.\n\n"
        msg += "<b>Note :- Chất lượng và tên tùy chỉnh là tùy chọn</b>\n\nVí dụ về chất lượng :- audio, 144, 240, 360, 480, 720, 1080, 2160."
        msg += "\n\nNếu bạn muốn sử dụng tên tệp tùy chỉnh, vui lòng nhập nó sau |"
        msg += f"\n\nVD :-\n<code>/{BotCommands.WatchCommand} https://youtu.be/UnyLfqpyi94 720 |My video</code>\n\n"
        msg += "Tệp này sẽ được tải xuống ở chất lượng 720p và tên của nó sẽ là <b>My video </b>"
        sendMessage(msg, bot, update)
        return
    try:
        if "|" in mssg:
            mssg = mssg.split("|")
            qual = mssg[0].split(" ")[2]
            if qual == "":
                raise IndexError
        else:
            qual = message_args[2]
        if qual != "audio":
            qual = f'bestvideo[height<={qual}]+bestaudio/best[height<={qual}]'
    except IndexError:
        qual = "bestvideo+bestaudio/best"
    try:
        name = name_args[1]
    except IndexError:
        name = ""
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None
    pswd = ""
    listener = MirrorListener(bot, update, pswd, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}', qual,
                           name)).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 17
0
def get_confirm(update, context):
    query = update.callback_query
    user_id = query.from_user.id
    data = query.data
    data = data.split(" ")
    qbdl = getDownloadByGid(data[1])
    if qbdl is None:
        query.answer(text="This task has been cancelled!", show_alert=True)
        query.message.delete()
    elif user_id != qbdl.listener().message.from_user.id:
        query.answer(text="Don't waste your time!", show_alert=True)
    elif data[0] == "pin":
        query.answer(text=data[2], show_alert=True)
    elif data[0] == "done":
        query.answer()
        qbdl.client().torrents_resume(torrent_hashes=data[2])
        sendStatusMessage(qbdl.listener().update, qbdl.listener().bot)
        query.message.delete()
Exemplo n.º 18
0
def mirror_status(update, context):
    with download_dict_lock:
        if len(download_dict) == 0:
            currentTime = get_readable_time(time() - botStartTime)
            total, used, free, _ = disk_usage('.')
            free = get_readable_file_size(free)
            message = 'No Active Downloads !\n___________________________'
            message += f"\n<b>CPU:</b> {cpu_percent()}% | <b>FREE:</b> {free}" \
                       f"\n<b>RAM:</b> {virtual_memory().percent}% | <b>UPTIME:</b> {currentTime}"
            reply_message = sendMessage(message, context.bot, update)
            Thread(target=auto_delete_message,
                   args=(context.bot, update.message, reply_message)).start()
            return
    index = update.effective_chat.id
    with status_reply_dict_lock:
        if index in status_reply_dict.keys():
            deleteMessage(context.bot, status_reply_dict[index])
            del status_reply_dict[index]
    sendStatusMessage(update, context.bot)
    deleteMessage(context.bot, update.message)
Exemplo n.º 19
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)
Exemplo n.º 20
0
def mirrorcf(update, context):

    bot = context.bot
    message_args = update.message.text.split(' ')
    try:
        link = message_args[1]
    except IndexError:
        link = ''

    LOGGER.info(link)
    link = link.strip()
    tag = None
    if not bot_utils.is_url(link) and not bot_utils.is_magnet(link):
        sendMessage('No download source provided', bot, update)
        return

    parsed_link = urlparse(link)
    headers = {"Content-Type": "application/json"}
    data = {
        "cmd": "request.get",
        "url": f"{parsed_link.scheme}://{parsed_link.netloc}",
        "maxTimeout": 60000
    }
    r = requests.post('http://localhost:8191/v1', headers=headers, json=data)
    solution = r.json()['solution']
    cf_clearance = solution['cookies'][0]
    cookie_string = f"{cf_clearance['name']}={cf_clearance['value']};"

    aria_options = {
        "header": f"Cookie:{cookie_string}",
        "user-agent": solution['userAgent']
    }

    listener = MirrorListener(bot, update, False, tag)
    ariaDlManager.add_download(f'{DOWNLOAD_DIR}/{listener.uid}/', [link],
                               listener, aria_options)
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            bot_utils.setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                                  update_all_messages))
Exemplo n.º 21
0
def _watch(bot: Bot, update: Update, args: list, isTar=False):
    try:
        link = args[0]
    except IndexError:
        sendMessage(
            f'/{BotCommands.WatchCommand} Give Youtube Video Link Or Playlist Link',
            bot, update)
        return
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        tag = reply_to.from_user.username
    else:
        tag = None

    listener = MirrorListener(bot, update, isTar, tag)
    ydl = YoutubeDLHelper(listener)
    threading.Thread(target=ydl.add_download,
                     args=(link, f'{DOWNLOAD_DIR}{listener.uid}')).start()
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 22
0
def add_gd_download(link: str, listener, gdtot):
    res, size, name, files = GoogleDriveHelper().helper(link)
    if res != "":
        sendMessage(res, listener.bot, listener.update)
        return
    if ZIP_UNZIP_LIMIT is not None:
        LOGGER.info('Checking File/Folder Size...')
        if size > ZIP_UNZIP_LIMIT * 1024**3:
            msg = f'Failed, Zip/Unzip limit is {ZIP_UNZIP_LIMIT}GB.\nYour File/Folder size is {get_readable_file_size(size)}.'
            sendMessage(msg, listener.bot, listener.update)
            return
    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 gdtot:
        drive.deletefile(link)
Exemplo n.º 23
0
def fembed(update, context):

    bot = context.bot
    message_args = update.message.text.split(' ')
    try:
        fembed_link = message_args[1]
    except IndexError:
        fembed_link = ''
    LOGGER.info(fembed_link)
    fembed_link = fembed_link.strip()
    tag = None
    if not bot_utils.is_url(fembed_link):
        sendMessage('No download source provided', bot, update)
        return

    aria_options = {}
    fembed_domain = re.match(r".*\/\/(.*?)\/.*", fembed_link,
                             re.MULTILINE).group(1)
    r = requests.get(fembed_link)
    data = BeautifulSoup(r.text, 'html.parser')
    try:
        name = data.find_all('title')[0].text.split(" - Free download")[0]
        aria_options.update({"out": name})
    except IndexError:
        pass
    fembed_id = fembed_link.split("f/")[1]
    fembed_api_link = f"https://{fembed_domain}/api/source/{fembed_id}"
    fembed_link = requests.post(fembed_api_link).json()['data'][-1]['file']

    listener = MirrorListener(bot, update, False, tag)
    ariaDlManager.add_download(f'{DOWNLOAD_DIR}/{listener.uid}/',
                               [fembed_link], listener, aria_options)
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            bot_utils.setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                                  update_all_messages))
 def __onDownloadStart(self):
     with download_dict_lock:
         download_dict[self.__listener.uid] = YoutubeDLDownloadStatus(
             self, self.__listener, self.__gid)
     sendStatusMessage(self.__listener.update, self.__listener.bot)
Exemplo n.º 25
0
def _mirror(bot, update, isZip=False, extract=False):
    mesg = update.message.text.split("\n")
    message_args = mesg[0].split(" ")
    name_args = mesg[0].split("|")
    try:
        link = message_args[1]
        print(link)
        if link.startswith("|") or link.startswith("pswd: "):
            link = ""
    except IndexError:
        link = ""
    try:
        name = name_args[1]
        name = name.strip()
        if name.startswith("pswd: "):
            name = ""
    except IndexError:
        name = ""
    try:
        ussr = urllib.parse.quote(mesg[1], safe="")
        pssw = urllib.parse.quote(mesg[2], safe="")
    except:
        ussr = ""
        pssw = ""
    if ussr != "" and pssw != "":
        link = link.split("://", maxsplit=1)
        link = f"{link[0]}://{ussr}:{pssw}@{link[1]}"
    pswd = re.search("(?<=pswd: )(.*)", update.message.text)
    if pswd is not None:
        pswd = pswd.groups()
        pswd = " ".join(pswd)
    LOGGER.info(link)
    link = link.strip()
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        file = None
        tag = reply_to.from_user.username
        media_array = [reply_to.document, reply_to.video, reply_to.audio]
        for i in media_array:
            if i is not None:
                file = i
                break

        if (not bot_utils.is_url(link) and not bot_utils.is_magnet(link)
                or len(link) == 0) and file is not None:
            if file.mime_type != "application/x-bittorrent":
                listener = MirrorListener(bot, update, pswd, isZip, tag,
                                          extract)
                tg_downloader = TelegramDownloadHelper(listener)
                tg_downloader.add_download(reply_to,
                                           f"{DOWNLOAD_DIR}{listener.uid}/",
                                           name)
                sendStatusMessage(update, bot)
                if len(Interval) == 0:
                    Interval.append(
                        setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                                    update_all_messages))
                return
            else:
                link = file.get_file().file_path
    else:
        tag = None
    if not bot_utils.is_url(link) and not bot_utils.is_magnet(link):
        sendMessage("No download source provided", bot, update)
        return

    try:
        link = direct_link_generator(link)
    except DirectDownloadLinkException as e:
        LOGGER.info(f"{link}: {e}")
    listener = MirrorListener(bot, update, pswd, isZip, tag, extract)
    if bot_utils.is_gdrive_link(link):
        if not isZip and not extract:
            sendMessage(f"Use /{BotCommands.CloneCommand} To Copy File/Folder",
                        bot, update)
            return
        res, size, name = gdriveTools.GoogleDriveHelper().clonehelper(link)
        if res != "":
            sendMessage(res, bot, update)
            return
        LOGGER.info(f"Download Name : {name}")
        drive = gdriveTools.GoogleDriveHelper(name, listener)
        gid = "".join(random.SystemRandom().choices(string.ascii_letters +
                                                    string.digits,
                                                    k=12))
        download_status = DownloadStatus(drive, size, listener, gid)
        with download_dict_lock:
            download_dict[listener.uid] = download_status
        if len(Interval) == 0:
            Interval.append(
                setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                            update_all_messages))
        sendStatusMessage(update, bot)
        drive.download(link)

    elif bot_utils.is_mega_link(
            link) and MEGA_KEY is not None and not BLOCK_MEGA_LINKS:
        mega_dl = MegaDownloader(listener)
        mega_dl.add_download(link, f"{DOWNLOAD_DIR}{listener.uid}/")
        sendStatusMessage(update, bot)
    elif bot_utils.is_mega_link(link) and BLOCK_MEGA_LINKS:
        sendMessage("Mega links are blocked. Dont try to mirror mega links.",
                    bot, update)
    else:
        ariaDlManager.add_download(link, f"{DOWNLOAD_DIR}{listener.uid}/",
                                   listener, name)
        sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 26
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)
Exemplo n.º 27
0
def _mirror(bot, update, isTar=False, extract=False):
    message_args = update.message.text.split(' ', 3)
    try:
        link = message_args[1]
    except IndexError:
        link = ''
    LOGGER.info(link)
    link = link.strip()
    try:
        options = message_args[2]
    except IndexError:
        options = None

    aria_options = {}
    if options:
        options = options.rsplit(",name=", 1)
        try:
            aria_options.update({"out": options[1]})
        except IndexError:
            pass
        left_options = options[0]
        options = left_options.split(",")
        for option in options:
            option_dict = option.split("=", 1)
            aria_options.update({option_dict[0]: option_dict[1]})

    reply_to = update.message.reply_to_message
    if reply_to is not None:
        file = None
        tag = reply_to.from_user.username
        media_array = [reply_to.document, reply_to.video, reply_to.audio]
        for i in media_array:
            if i is not None:
                file = i
                break

        if len(link) == 0:
            if file is not None:
                if file.mime_type != "application/x-bittorrent":
                    listener = MirrorListener(bot, update, isTar, tag, extract)
                    tg_downloader = TelegramDownloadHelper(listener)
                    tg_downloader.add_download(
                        reply_to, f'{DOWNLOAD_DIR}{listener.uid}/')
                    sendStatusMessage(update, bot)
                    if len(Interval) == 0:
                        Interval.append(
                            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL,
                                        update_all_messages))
                    return
                else:
                    link = file.get_file().file_path
    else:
        tag = None
    if not bot_utils.is_url(link) and not bot_utils.is_magnet(link):
        sendMessage('No download source provided', bot, update)
        return

    try:
        link, cookies = direct_link_generator(link)
        if cookies:
            aria_options.update({"header": f"Cookie:{cookies}"})
    except DirectDownloadLinkException as e:
        LOGGER.info(f'{link}: {e}')
    listener = MirrorListener(bot, update, isTar, tag, extract)
    if bot_utils.is_mega_link(link) and MEGA_KEY is not None:
        mega_dl = MegaDownloader(listener)
        mega_dl.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/')
    else:
        ariaDlManager.add_download(f'{DOWNLOAD_DIR}/{listener.uid}/', [link],
                                   listener, aria_options)
    sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemplo n.º 28
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()