def _mirror(bot, update, isTar=False): message_args = update.message.text.split(' ') try: link = message_args[1] except IndexError: link = '' LOGGER.info(link) link = link.strip() if len(link) == 0: if update.message.reply_to_message is not None: document = update.message.reply_to_message.document if document is not None and document.mime_type == "application/x-bittorrent": link = document.get_file().file_path else: sendMessage('Only torrent files can be mirrored from telegram', bot, update) return if not bot_utils.is_url(link) and not bot_utils.is_magnet(link): sendMessage('No download source provided', bot, update) return listener = MirrorListener(bot, update, isTar) aria = aria2_download.AriaDownloadHelper(listener) aria.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/') sendStatusMessage(update, bot) if len(Interval) == 0: Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
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))
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.\n<b>Note :- Quality is optional</b> \n<i><u>If you didn't mention Quality, Highest Quality will be Uploaded To Google Drive.</u></i> \n\n<b> Type #watch_quality for example.</b>" 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() msg = f"<b>Your Requested YT-DL Link has been added to the </b><b>/{BotCommands.StatusCommand}</b>" sendMessage(msg, bot, update) if len(Interval) == 0: Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
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))
def download(self, link): self.is_downloading = True file_id = self.getIdFromUrl(link) if USE_SERVICE_ACCOUNTS: self.service_account_count = len(os.listdir("accounts")) self.updater = setInterval(self.update_interval, self._on_download_progress) try: meta = self.getFileMetadata(file_id) path = f"{DOWNLOAD_DIR}{self.__listener.uid}/" if meta.get("mimeType") == self.__G_DRIVE_DIR_MIME_TYPE: self.download_folder(file_id, path, meta.get('name')) else: os.makedirs(path) self.download_file(file_id, path, meta.get('name'), meta.get('mimeType')) except Exception as err: err = str(err).replace('>', '').replace('<', '') LOGGER.error(err) if "downloadQuotaExceeded" in str(err): err = "Download Quota Exceeded." self.__listener.onDownloadError(err) return finally: self.updater.cancel() if self.is_cancelled: return self.__listener.onDownloadComplete()
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))
def _mirror(bot, update, isTar=False, extract=False): message_args = update.message.text.split(' ') try: link = message_args[1] except IndexError: link = '' 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 len(link) == 0: if file is not None: if file.mime_type != "application/x-bittorrent": listener = MirrorListener(bot, update, isTar, tag) 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 = direct_link_generator(link) except DirectDownloadLinkException as e: LOGGER.info(f'{link}: {e}') listener = MirrorListener(bot, update, isTar, tag, extract) ariaDlManager.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/',listener) sendStatusMessage(update, bot) if len(Interval) == 0: Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
def _mirror(bot, update, isTar=False): message_args = update.message.text.split(' ') try: link = message_args[1] except IndexError: link = '' 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 len(link) == 0: if file is not None: if file.mime_type != "application/x-bittorrent": listener = MirrorListener(bot, update, isTar, tag) 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('𝐍𝐨 𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝 𝐬𝐨𝐮𝐫𝐜𝐞 𝐩𝐫𝐨𝐯𝐢𝐝𝐞𝐝. 𝐅𝐨𝐫𝐦𝐚𝐭 /𝚖𝚒𝚛𝚛𝚘𝚛𝚃𝚘𝚛𝚛𝚎𝚗𝚝𝚜𝚝𝚘𝚛𝚎𝚋𝚘𝚝 𝐦𝐚𝐠𝐧𝐞𝐭𝐥𝐢𝐧𝐤', bot, update) return try: link = direct_link_generator(link) except DirectDownloadLinkException as e: LOGGER.info(f'{link}: {e}') listener = MirrorListener(bot, update, isTar, tag) aria = aria2_download.AriaDownloadHelper(listener) aria.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/') sendStatusMessage(update, bot) if len(Interval) == 0: Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
def __onDownloadStart(self, name, size, gid): self.__periodic = setInterval(self.POLLING_INTERVAL, self.__onInterval) with download_dict_lock: download_dict[self.__listener.uid] = MegaDownloadStatus(self, self.__listener) with self.__resource_lock: self.__name = name self.__size = size self.__gid = gid self.__listener.onDownloadStarted()
def upload(self, file_name: str): if USE_SERVICE_ACCOUNTS: self.service_account_count = len(os.listdir("accounts")) self.__listener.onUploadStarted() file_dir = f"{DOWNLOAD_DIR}{self.__listener.message.message_id}" file_path = f"{file_dir}/{file_name}" LOGGER.info("Uploading File: " + file_path) self.start_time = time.time() self.updater = setInterval(self.update_interval, self._on_upload_progress) if os.path.isfile(file_path): try: mime_type = get_mime_type(file_path) link = self.upload_file(file_path, file_name, mime_type, bot.parent_id) if link is None: raise Exception('Upload has been manually cancelled') LOGGER.info("Uploaded To G-Drive: " + file_path) except Exception as e: if isinstance(e, RetryError): LOGGER.info( f"Total Attempts: {e.last_attempt.attempt_number}") err = e.last_attempt.exception() else: err = e LOGGER.error(err) self.__listener.onUploadError(str(err)) return finally: self.updater.cancel() else: try: dir_id = self.create_directory( os.path.basename(os.path.abspath(file_name)), bot.parent_id) result = self.upload_dir(file_path, dir_id) if result is None: raise Exception('Upload has been manually cancelled!') LOGGER.info("Uploaded To G-Drive: " + file_name) link = f"https://drive.google.com/folderview?id={dir_id}" except Exception as e: if isinstance(e, RetryError): LOGGER.info( f"Total Attempts: {e.last_attempt.attempt_number}") err = e.last_attempt.exception() else: err = e LOGGER.error(err) self.__listener.onUploadError(str(err)) return finally: self.updater.cancel() LOGGER.info(download_dict) self.__listener.onUploadComplete(link) LOGGER.info("Deleting downloaded file/folder..") return link
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))
def upload(self, file_name: str): self.is_downloading = False self.is_uploading = True file_dir = f"{DOWNLOAD_DIR}{self.__listener.message.message_id}" file_path = f"{file_dir}/{file_name}" size = get_readable_file_size(get_path_size(file_path)) LOGGER.info("Uploading File: " + file_path) self.updater = setInterval(self.update_interval, self._on_upload_progress) try: if ospath.isfile(file_path): mime_type = get_mime_type(file_path) link = self.__upload_file(file_path, file_name, mime_type, parent_id) if self.is_cancelled: return if link is None: raise Exception('Upload has been manually cancelled') LOGGER.info("Uploaded To G-Drive: " + file_path) else: mime_type = 'Folder' dir_id = self.__create_directory( ospath.basename(ospath.abspath(file_name)), parent_id) result = self.__upload_dir(file_path, dir_id) if result is None: raise Exception('Upload has been manually cancelled!') link = f"https://drive.google.com/folderview?id={dir_id}" if self.is_cancelled: return LOGGER.info("Uploaded To G-Drive: " + file_name) except Exception as e: if isinstance(e, RetryError): LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}") err = e.last_attempt.exception() else: err = e LOGGER.error(err) self.__listener.onUploadError(str(err)) self.is_cancelled = True finally: self.updater.cancel() if self.is_cancelled: if mime_type == 'Folder': LOGGER.info("Deleting uploaded data from Drive...") link = f"https://drive.google.com/folderview?id={dir_id}" self.deletefile(link) return self.__listener.onUploadComplete(link, size, self.__total_files, self.__total_folders, mime_type, self.name)
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/XsX3ATc3FbA 720 |Hello World</code>\n\n" msg += "This file will be downloaded in 720p quality and it's name will be <b>Hello World</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() sendMessage( f"<b>Your YouTube Link has been ADDED for Mirror 😋</b>\n👉 Check /{BotCommands.StatusCommand}", bot, update) if len(Interval) == 0: Interval.append( setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
def sendStatusMessage(msg, bot): if len(Interval) == 0: Interval.append( setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages)) total, used, free = shutil.disk_usage('.') free = get_readable_file_size(free) currentTime = get_readable_time(time.time() - botStartTime) progress, buttons = get_readable_message() if progress is None: progress, buttons = get_readable_message() progress += f"<b>CPU:</b> <code>{psutil.cpu_percent()}%</code>" \ f" <b>RAM:</b> <code>{psutil.virtual_memory().percent}%</code>" \ f" <b>DISK:</b> <code>{psutil.disk_usage('/').percent}%</code>" with download_dict_lock: dlspeed_bytes = 0 uldl_bytes = 0 for download in list(download_dict.values()): speedy = download.speed() if download.status() == MirrorStatus.STATUS_DOWNLOADING: if 'K' in speedy: dlspeed_bytes += float(speedy.split('K')[0]) * 1024 elif 'M' in speedy: dlspeed_bytes += float(speedy.split('M')[0]) * 1048576 if download.status() == MirrorStatus.STATUS_UPLOADING: if 'KB/s' in speedy: uldl_bytes += float(speedy.split('K')[0]) * 1024 elif 'MB/s' in speedy: uldl_bytes += float(speedy.split('M')[0]) * 1048576 dlspeed = get_readable_file_size(dlspeed_bytes) ulspeed = get_readable_file_size(uldl_bytes) progress += f"\n<b>FREE:</b> <code>{free}</code> | <b>UPTIME:</b> <code>{currentTime}</code>\n<b>DL:</b> <code>{dlspeed}/s</code> 🔻 | <b>UL:</b> <code>{ulspeed}/s</code> 🔺\n" with status_reply_dict_lock: if msg.message.chat.id in list(status_reply_dict.keys()): try: message = status_reply_dict[msg.message.chat.id] deleteMessage(bot, message) del status_reply_dict[msg.message.chat.id] except Exception as e: LOGGER.error(str(e)) del status_reply_dict[msg.message.chat.id] pass if buttons == "": message = sendMessage(progress, bot, msg) else: message = sendMarkup(progress, bot, msg, buttons) status_reply_dict[msg.message.chat.id] = message
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))
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] |[Custom Name] 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\n• <b>If you want to use Custom Filename</b>, enter it after |" msg += f"\n\nExample :-\n<code>/{BotCommands.WatchCommand} https://youtu.be/QMOadtGpwlw 720 |Ikson - New Day </code>\n\n" msg += "This file will be downloaded in 720p quality and it's name will be <b>Ikson - Alive</b>\n\n" msg += "• <b>if you want to convert to .mp3 / music</b>" msg += f"\n\nExample :-\n<code>/{BotCommands.WatchCommand} https://youtu.be/QMOadtGpwlw audio |Ikson - New Day </code>\n\n" msg += "This file will be downloaded in .mp3/audio and it's name will be <b>Ikson - Alive.mp3</b>\n\n" 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 _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))
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, f'{DOWNLOAD_DIR}{listener.uid}')).start() sendStatusMessage(update, bot) if len(Interval) == 0: Interval.append(setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
def sendStatusMessage(msg, bot): if len(Interval) == 0: Interval.append( setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages)) progress, buttons = get_readable_message() with status_reply_dict_lock: if msg.message.chat.id in list(status_reply_dict.keys()): try: message = status_reply_dict[msg.message.chat.id] deleteMessage(bot, message) del status_reply_dict[msg.message.chat.id] except Exception as e: LOGGER.error(str(e)) del status_reply_dict[msg.message.chat.id] if buttons == "": message = sendMessage(progress, bot, msg) else: message = sendMarkup(progress, bot, msg, buttons) status_reply_dict[msg.message.chat.id] = message
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))
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 download(self, link): self.is_downloading = True file_id = self.__getIdFromUrl(link) self.updater = setInterval(self.update_interval, self._on_download_progress) try: meta = self.__getFileMetadata(file_id) path = f"{DOWNLOAD_DIR}{self.__listener.uid}/" if meta.get("mimeType") == self.__G_DRIVE_DIR_MIME_TYPE: self.__download_folder(file_id, path, meta.get('name')) else: makedirs(path) self.__download_file(file_id, path, meta.get('name'), meta.get('mimeType')) except Exception as err: if isinstance(err, RetryError): LOGGER.info( f"Total Attempts: {err.last_attempt.attempt_number}") err = err.last_attempt.exception() err = str(err).replace('>', '').replace('<', '') LOGGER.error(err) if "downloadQuotaExceeded" in str(err): err = "Download Quota Exceeded." elif "File not found" in str(err): token_service = self.__alt_authorize() if token_service is not None: self.__service = token_service self.updater.cancel() return self.download(link) self.__listener.onDownloadError(err) self.is_cancelled = True finally: self.updater.cancel() if self.is_cancelled: return self.__listener.onDownloadComplete()
def _mirror(bot, update, isTar=False, extract=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>' msg = f"User: {name} {username} (<code>{update.message.from_user.id}</code>)\n" message_args = update.message.text.split(' ') name_args = update.message.text.split('|') try: link = message_args[1] 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 = '' 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: if file is not None: if file.mime_type != "application/x-bittorrent": listener = MirrorListener(bot, update, pswd, isTar, tag, extract) tg_downloader = TelegramDownloadHelper(listener) tg_downloader.add_download( reply_to, f'{DOWNLOAD_DIR}{listener.uid}/', name) msg += f"Message: <code>{file.mime_type}</code> | <code>{download_dict[listener.uid].name()}</code> | {download_dict[listener.uid].size()}" sendMessage(msg, bot, update) 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, isTar, tag, extract) if bot_utils.is_mega_link(link): link_type = get_mega_link_type(link) if link_type == "folder" and BLOCK_MEGA_FOLDER: sendMessage("Mega folder are blocked!", bot, update) elif BLOCK_MEGA_LINKS: sendMessage( "Mega links are blocked bcoz mega downloading is too much unstable and buggy. mega support will be added back after fix", bot, update) else: mega_dl = MegaDownloadHelper() mega_dl.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/', listener) msg += f"Message: {update.message.text}" sendMessage(msg, bot, update) sendStatusMessage(update, bot) else: ariaDlManager.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/', listener, name) if reply_to is not None: msg += f"Message: <code>{file.mime_type}</code> | <code>{file.file_name}</code> | {get_readable_file_size(file.file_size)}" else: msg += 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))
def _mirror(bot, update, isTar=False, extract=False): message_args = update.message.text.split(' ') name_args = update.message.text.split('|') try: link = message_args[1] except IndexError: link = '' try: name = name_args[1] except IndexError: name = '' 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: if file is not None: if file.mime_type != "application/x-bittorrent": listener = MirrorListener(bot, update, pswd, isTar, 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, isTar, tag, extract) if bot_utils.is_mega_link(link): if BLOCK_MEGA_LINKS: sendMessage( "Mega links are blocked bcoz mega downloading is too much unstable and buggy. mega support will be added back after fix", bot, update) else: mega_dl = MegaDownloadHelper() mega_dl.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/', listener, name) sendStatusMessage(update, bot) 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))
def _mirror(bot, update, isTar=False, extract=False): mesg = update.message.text.split("\n") message_args = mesg[0].split(" ") name_args = mesg[0].split("|") try: link = message_args[1] 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 None: tag = None else: 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": link = file.get_file().file_path else: listener = MirrorListener(bot, update, pswd, isTar, 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 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, isTar, tag, extract) if bot_utils.is_mega_link(link): if BLOCK_MEGA_LINKS: sendMessage( "Mega links are blocked bcoz mega downloading is too much unstable and buggy. mega support will be added back after fix", bot, update, ) else: mega_dl = MegaDownloadHelper() mega_dl.add_download(link, f"{DOWNLOAD_DIR}/{listener.uid}/", listener) sendStatusMessage(update, bot) 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))
def _mirror(bot, update, isTar=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: if file is not None: if file.mime_type != "application/x-bittorrent": listener = MirrorListener(bot, update, pswd, isTar, 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, isTar, tag, extract) if bot_utils.is_mega_link(link): link_type = get_mega_link_type(link) if link_type == "folder" and BLOCK_MEGA_FOLDER: sendMessage("Mega folder are blocked!", bot, update) elif BLOCK_MEGA_LINKS: sendMessage("Mega links are blocked!", bot, update) else: mega_dl = MegaDownloadHelper() mega_dl.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/', listener) sendStatusMessage(update, bot) 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))
def _mirror(bot, update, isTar=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: if file is not None: if file.mime_type != "application/x-bittorrent": listener = MirrorListener(bot, update, pswd, isTar, 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, isTar, tag, extract) if bot_utils.is_gdrive_link(link): if not isTar 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: if BLOCK_MEGA_LINKS: sendMessage("Mega Links Are Blocked.", bot, update) else: mega_dl = MegaDownloader(listener) mega_dl.add_download(link, f'{DOWNLOAD_DIR}{listener.uid}/') sendStatusMessage(update, bot) 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))
def upload(self, file_name: str): self.is_downloading = False self.is_uploading = True if USE_SERVICE_ACCOUNTS: self.service_account_count = len(os.listdir("accounts")) self.__listener.onUploadStarted() file_dir = f"{DOWNLOAD_DIR}{self.__listener.message.message_id}" file_path = f"{file_dir}/{file_name}" size = get_readable_file_size(get_path_size(file_path)) LOGGER.info("Uploading File: " + file_path) self.updater = setInterval(self.update_interval, self._on_upload_progress) if os.path.isfile(file_path): try: mime_type = get_mime_type(file_path) link = self.upload_file(file_path, file_name, mime_type, parent_id) if self.is_cancelled: return if link is None: raise Exception('Upload has been manually cancelled') LOGGER.info("Uploaded To G-Drive: " + file_path) except Exception as e: if isinstance(e, RetryError): LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}") err = e.last_attempt.exception() else: err = e LOGGER.error(err) self.__listener.onUploadError(str(err)) return finally: self.updater.cancel() if self.is_cancelled: return else: try: dir_id = self.create_directory(os.path.basename(os.path.abspath(file_name)), parent_id) result = self.upload_dir(file_path, dir_id) if result is None: raise Exception('Upload has been manually cancelled!') link = f"https://drive.google.com/folderview?id={dir_id}" if self.is_cancelled: LOGGER.info("Deleting uploaded data from Drive...") msg = self.deletefile(link) LOGGER.info(f"{msg}") return LOGGER.info("Uploaded To G-Drive: " + file_name) except Exception as e: if isinstance(e, RetryError): LOGGER.info(f"Total Attempts: {e.last_attempt.attempt_number}") err = e.last_attempt.exception() else: err = e LOGGER.error(err) self.__listener.onUploadError(str(err)) return finally: self.updater.cancel() if self.is_cancelled: return files = self.total_files folders = self.total_folders typ = self.typee self.__listener.onUploadComplete(link, size, files, folders, typ) return link
def _mirror(bot, update, isTar=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: if file is not None: if file.mime_type != "application/x-bittorrent": listener = MirrorListener(bot, update, pswd, isTar, tag, extract) tg_downloader = TelegramDownloadHelper(listener) tg_downloader.add_download( reply_to, f'{DOWNLOAD_DIR}{listener.uid}/', name) 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}') 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, tag, extract) 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 = gdriveTools.GoogleDriveHelper().clonehelper(link) if res != "": sendMessage(res, bot, update) return if TAR_UNZIP_LIMIT is not None: LOGGER.info(f'Checking File/Folder Size') limit = TAR_UNZIP_LIMIT limit = limit.split(' ', maxsplit=1) limitint = int(limit[0]) msg = f'Failed, Tar/Unzip limit is {TAR_UNZIP_LIMIT}.\nYour File/Folder size is {get_readable_file_size(size)}.' if 'G' in limit[1] or 'g' in limit[1]: if size > limitint * 1024**3: sendMessage(msg, listener.bot, listener.update) return elif 'T' in limit[1] or 't' in limit[1]: if size > limitint * 1024**4: 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 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): link_type = get_mega_link_type(link) if link_type == "folder" and BLOCK_MEGA_FOLDER: sendMessage("Mega folder are blocked!", bot, update) elif BLOCK_MEGA_LINKS: sendMessage("Mega links are blocked!", bot, update) else: mega_dl = MegaDownloadHelper() mega_dl.add_download(link, f'{DOWNLOAD_DIR}/{listener.uid}/', listener) 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))
def add_torrent(self, link, dire, listener, qbitsel): self.client = get_client() self.listener = listener is_file = False count = 0 pincode = "" markup = None try: if os.path.exists(link): is_file = True self.ext_hash = get_hash_file(link) else: self.ext_hash = get_hash_magnet(link) tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash) if len(tor_info) > 0: sendMessage("This torrent is already in list.", listener.bot, listener.update) return if is_file: op = self.client.torrents_add(torrent_files=[link], save_path=dire) os.remove(link) else: op = self.client.torrents_add(link, save_path=dire) if op.lower() == "ok.": LOGGER.info(f"QbitDownload started: {self.ext_hash}") tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash) if len(tor_info) == 0: while True: if time.time() - self.meta_time >= 300: sendMessage("The torrent was not added. report when u see this error", listener.bot, listener.update) return False tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash) if len(tor_info) > 0: break else: sendMessage("This is an unsupported/invalid link.", listener.bot, listener.update) return gid = ''.join(random.SystemRandom().choices(string.ascii_letters + string.digits, k=14)) with download_dict_lock: download_dict[listener.uid] = QbDownloadStatus(gid, listener, self.ext_hash, self.client) self.updater = setInterval(self.update_interval, self.update) tor_info = tor_info[0] if BASE_URL is not None and qbitsel: if not is_file and (tor_info.state == "checkingResumeData" or tor_info.state == "metaDL"): meta = sendMessage("Downloading Metadata...Please wait then you can select files or mirror torrent file if it have low seeders", listener.bot, listener.update) while True: tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash) if len(tor_info) == 0: deleteMessage(listener.bot, meta) return False tor_info = tor_info[0] if tor_info.state == "metaDL" or tor_info.state == "checkingResumeData": time.sleep(1) else: break deleteMessage(listener.bot, meta) for n in str(self.ext_hash): if n.isdigit(): pincode += str(n) count += 1 if count == 4: break URL = f"{BASE_URL}/slam/files/{self.ext_hash}" pindata = f"pin {gid} {pincode}" donedata = f"done {gid} {self.ext_hash}" buttons = button_build.ButtonMaker() buttons.buildbutton("Select Files", URL) buttons.sbutton("Pincode", pindata) buttons.sbutton("Done Selecting", donedata) QBBUTTONS = InlineKeyboardMarkup(buttons.build_menu(2)) msg = "Your download paused. Choose files then press Done Selecting button to start downloading." markup = sendMarkup(msg, listener.bot, listener.update, QBBUTTONS) self.client.torrents_pause(torrent_hashes=self.ext_hash) with download_dict_lock: download = download_dict[listener.uid] download.markup = markup else: sendStatusMessage(listener.update, listener.bot) except qba.UnsupportedMediaType415Error as e: LOGGER.error(str(e)) sendMessage("This is an unsupported/invalid link. {str(e)}", listener.bot, listener.update) except Exception as e: LOGGER.error(str(e)) sendMessage(str(e), listener.bot, listener.update) self.client.torrents_delete(torrent_hashes=self.ext_hash)