Exemplo n.º 1
0
def cloneNode(update, context):
    args = update.message.text.split(" ", maxsplit=1)
    if len(args) > 1:
        link = args[1]
        gd = gdriveTools.GoogleDriveHelper()
        res, size, name, files = gd.clonehelper(link)
        if res != "":
            sendMessage(res, context.bot, update)
            return
        if STOP_DUPLICATE:
            LOGGER.info('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:
            result = check_limit(size, CLONE_LIMIT)
            if result:
                msg2 = f'Failed, Clone limit is {CLONE_LIMIT}.\nYour File/Folder size is {get_readable_file_size(size)}.'
                sendMessage(msg2, context.bot, update)
                return
        if files < 15:
            msg = sendMessage(f"Cloning: <code>{link}</code>", context.bot, update)
            result, button = gd.clone(link)
            deleteMessage(context.bot, msg)
        else:
            drive = gdriveTools.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
        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}'
            men = f'{uname} '
        if button in ["cancelled", ""]:
            sendMessage(men + result, context.bot, update)
        else:
            sendMarkup(result + cc, context.bot, update, button)
    else:
        sendMessage('Provide G-Drive Shareable Link to Clone.', context.bot, update)
Exemplo n.º 2
0
 def add_download(mega_link: str, path: str, listener):
     if MEGA_API_KEY is None:
         raise MegaDownloaderException('Mega API KEY not provided! Cannot mirror Mega links')
     executor = AsyncExecutor()
     api = MegaApi(MEGA_API_KEY, None, None, 'telegram-mirror-bot')
     global listeners
     mega_listener = MegaAppListener(executor.continue_event, listener)
     listeners.append(mega_listener)
     api.addListener(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,'TgBot')
         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:
         LOGGER.info('Checking File/Folder if already in Drive')
         mname = node.getName()
         if listener.isTar:
             mname = mname + ".tar"
         if listener.extract:
             smsg = None
         else:
             gd = GoogleDriveHelper()
             smsg, button = gd.drive_list(mname)
         if smsg:
             msg1 = "File/Folder is already available in Drive.\nHere are the search results:"
             sendMarkup(msg1, listener.bot, listener.update, button)
             executor.continue_event.set()
             return
     if MEGA_LIMIT is not None or TAR_UNZIP_LIMIT is not None:
         size = api.getSize(node)
         if listener.isTar or listener.extract:
             is_tar_ext = True
             msg3 = f'Failed, Tar/Unzip limit is {TAR_UNZIP_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
         else:
             is_tar_ext = False
             msg3 = f'Failed, Mega limit is {MEGA_LIMIT}.\nYour File/Folder size is {get_readable_file_size(api.getSize(node))}.'
         result = check_limit(size, MEGA_LIMIT, TAR_UNZIP_LIMIT, is_tar_ext)
         if result:
             sendMessage(msg3, listener.bot, listener.update)
             executor.continue_event.set()
             return
     with download_dict_lock:
         download_dict[listener.uid] = MegaDownloadStatus(mega_listener, listener)
     os.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))
Exemplo n.º 3
0
def _mirror(bot,
            update,
            isTar=False,
            extract=False,
            isZip=False,
            isQbit=False):
    mesg = update.message.text.split('\n')
    message_args = mesg[0].split(' ')
    name_args = mesg[0].split('|')
    qbitsel = False
    try:
        link = message_args[1]
        if link in ["qb", "qbs"]:
            isQbit = True
            if link == "qbs":
                qbitsel = True
            link = message_args[2]
            if bot_utils.is_url(link) and not bot_utils.is_magnet(link):
                resp = requests.get(link)
                if resp.status_code == 200:
                    file_name = str(time.time()).replace(".", "") + ".torrent"
                    with open(file_name, "wb") as f:
                        f.write(resp.content)
                    link = f"{file_name}"
                else:
                    sendMessage(
                        "ERROR: link got HTTP response:" + resp.status_code,
                        bot, update)
                    return
        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)
    if link != '':
        LOGGER.info(link)
    link = link.strip()
    reply_to = update.message.reply_to_message
    if reply_to is not None:
        file = None
        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 isQbit:
                file_name = str(time.time()).replace(".", "") + ".torrent"
                file.get_file().download(custom_path=f"{file_name}")
                link = f"{file_name}"
            elif file.mime_type != "application/x-bittorrent":
                listener = MirrorListener(bot, update, pswd, isTar, extract,
                                          isZip)
                tg_downloader = TelegramDownloadHelper(listener)
                ms = update.message
                tg_downloader.add_download(ms,
                                           f'{DOWNLOAD_DIR}{listener.uid}/',
                                           name)
                return
            else:
                link = file.get_file().file_path

    if not bot_utils.is_url(link) and not bot_utils.is_magnet(link):
        sendMessage('No download source provided', bot, update)
        return
    if not os.path.exists(link) and not bot_utils.is_mega_link(
            link) and not bot_utils.is_gdrive_link(
                link) and not bot_utils.is_magnet(link):
        try:
            link = direct_link_generator(link)
        except DirectDownloadLinkException as e:
            LOGGER.info(e)
            if "ERROR:" in str(e):
                sendMessage(f"{e}", bot, update)
                return
            if "Youtube" in str(e):
                sendMessage(f"{e}", bot, update)
                return

    listener = MirrorListener(bot, update, pswd, isTar, extract, isZip, isQbit)

    if bot_utils.is_gdrive_link(link):
        if not isTar and not extract:
            sendMessage(
                f"Use /{BotCommands.CloneCommand} to clone Google Drive file/folder\nUse /{BotCommands.TarMirrorCommand} to make tar of Google Drive folder\nUse /{BotCommands.UnzipMirrorCommand} to extracts archive Google Drive file",
                bot, update)
            return
        res, size, name, files = gdriveTools.GoogleDriveHelper().clonehelper(
            link)
        if res != "":
            sendMessage(res, bot, update)
            return
        if TAR_UNZIP_LIMIT is not None:
            result = bot_utils.check_limit(size, TAR_UNZIP_LIMIT)
            if result:
                msg = f'Failed, Tar/Unzip limit is {TAR_UNZIP_LIMIT}.\nYour File/Folder size is {get_readable_file_size(size)}.'
                sendMessage(msg, listener.bot, listener.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
        sendStatusMessage(update, bot)
        drive.download(link)

    elif bot_utils.is_mega_link(link):
        if BLOCK_MEGA_LINKS:
            sendMessage("Mega links are blocked!", bot, update)
            return
        link_type = bot_utils.get_mega_link_type(link)
        if link_type == "folder" and BLOCK_MEGA_FOLDER:
            sendMessage("Mega folder are blocked!", bot, update)
        else:
            mega_dl = MegaDownloadHelper()
            mega_dl.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/',
                                 listener)

    elif isQbit and (bot_utils.is_magnet(link) or os.path.exists(link)):
        qbit = qbittorrent()
        qbit.add_torrent(link, f'{DOWNLOAD_DIR}{listener.uid}/', listener,
                         qbitsel)

    else:
        ariaDlManager.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/',
                                   listener, name)
        sendStatusMessage(update, bot)
Exemplo n.º 4
0
 def update(self):
     tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
     if len(tor_info) == 0:
         self.client.auth_log_out()
         self.updater.cancel()
         return
     try:
         tor_info = tor_info[0]
         if tor_info.state == "metaDL":
             self.stalled_time = time.time()
             if time.time(
             ) - self.meta_time >= 999999999:  # timeout while downloading metadata
                 self.client.torrents_pause(torrent_hashes=self.ext_hash)
                 time.sleep(0.3)
                 self.listener.onDownloadError("Dead Torrent!")
                 self.client.torrents_delete(torrent_hashes=self.ext_hash)
                 self.client.auth_log_out()
                 self.updater.cancel()
                 return
         elif tor_info.state == "downloading":
             self.stalled_time = time.time()
             if (TORRENT_DIRECT_LIMIT is not None
                     or TAR_UNZIP_LIMIT is not None) and not self.checked:
                 if self.listener.isTar or self.listener.extract:
                     is_tar_ext = True
                     mssg = f'Tar/Unzip limit is {TAR_UNZIP_LIMIT}'
                 else:
                     is_tar_ext = False
                     mssg = f'Torrent/Direct limit is {TORRENT_DIRECT_LIMIT}'
                 size = tor_info.size
                 result = check_limit(size, TORRENT_DIRECT_LIMIT,
                                      TAR_UNZIP_LIMIT, is_tar_ext)
                 self.checked = True
                 if result:
                     self.client.torrents_pause(
                         torrent_hashes=self.ext_hash)
                     time.sleep(0.3)
                     self.listener.onDownloadError(
                         f"{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}"
                     )
                     self.client.torrents_delete(
                         torrent_hashes=self.ext_hash)
                     self.client.auth_log_out()
                     self.updater.cancel()
                     return
         elif tor_info.state == "stalledDL":
             if time.time(
             ) - self.stalled_time >= 999999999:  # timeout after downloading metadata
                 self.client.torrents_pause(torrent_hashes=self.ext_hash)
                 time.sleep(0.3)
                 self.listener.onDownloadError("Dead Torrent!")
                 self.client.torrents_delete(torrent_hashes=self.ext_hash)
                 self.client.auth_log_out()
                 self.updater.cancel()
                 return
         elif tor_info.state == "error":
             self.client.torrents_pause(torrent_hashes=self.ext_hash)
             time.sleep(0.3)
             self.listener.onDownloadError(
                 "No enough space for this torrent on device")
             self.client.torrents_delete(torrent_hashes=self.ext_hash)
             self.client.auth_log_out()
             self.updater.cancel()
             return
         elif tor_info.state == "uploading" or tor_info.state.lower(
         ).endswith("up"):
             self.client.torrents_pause(torrent_hashes=self.ext_hash)
             if self.qbitsel:
                 for dirpath, subdir, files in os.walk(f"{self.dire}",
                                                       topdown=False):
                     for file in files:
                         if fnmatch(file, "*.!qB"):
                             os.remove(os.path.join(dirpath, file))
                     for folder in subdir:
                         if fnmatch(folder, ".unwanted"):
                             shutil.rmtree(os.path.join(dirpath, folder))
                 for dirpath, subdir, files in os.walk(f"{self.dire}",
                                                       topdown=False):
                     if not os.listdir(dirpath):
                         os.rmdir(dirpath)
             self.listener.onDownloadComplete()
             self.client.torrents_delete(torrent_hashes=self.ext_hash)
             self.client.auth_log_out()
             self.updater.cancel()
     except:
         self.updater.cancel()