def sendStatusMessage(msg, bot): progress = get_readable_message() progress += f"<b>🖥 CPU:</b> {psutil.cpu_percent()}%\n" \ f"<b>🚀 RAM:</b> {psutil.virtual_memory().percent}%\n" \ f"<b>📦 DISK:</b> {psutil.disk_usage('/').percent}%\n" 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 'KiB/s' in speedy: dlspeed_bytes += float(speedy.split('K')[0]) * 1024 elif 'MiB/s' 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>DL:</b>{dlspeed}ps 🔻| <b>UL:</b>{ulspeed}ps 🔺\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] message = sendMessage(progress, bot, msg) status_reply_dict[msg.message.chat.id] = message
def editMessage(text: str, message: Message, reply_markup=None): try: bot.edit_message_text(text=text, message_id=message.message_id, chat_id=message.chat.id,reply_markup=reply_markup, parse_mode='HTMl') except Exception as e: LOGGER.error(str(e))
def shell(update: Update, context: CallbackContext): message = update.effective_message cmd = message.text.split(' ', 1) if len(cmd) == 1: message.reply_text('No command to execute was given.') return cmd = cmd[1] process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() reply = '' stderr = stderr.decode() stdout = stdout.decode() if stdout: reply += f"*Stdout*\n`{stdout}`\n" LOGGER.info(f"Shell - {cmd} - {stdout}") if stderr: reply += f"*Stderr*\n`{stderr}`\n" LOGGER.error(f"Shell - {cmd} - {stderr}") if len(reply) > 3000: with open('shell_output.txt', 'w') as file: file.write(reply) with open('shell_output.txt', 'rb') as doc: context.bot.send_document(document=doc, filename=doc.name, reply_to_message_id=message.message_id, chat_id=message.chat_id) else: message.reply_text(reply, parse_mode=ParseMode.MARKDOWN)
def sendMessage(text: str, bot, update: Update): try: return bot.send_message(update.message.chat_id, reply_to_message_id=update.message.message_id, text=text, parse_mode='HTMl') except Exception as e: LOGGER.error(str(e))
def sendMarkup(text: str, bot, update: Update, reply_markup: InlineKeyboardMarkup): try: return bot.send_message(update.message.chat_id, reply_to_message_id=update.message.message_id, text=text, reply_markup=reply_markup, parse_mode='HTMl') except Exception as e: LOGGER.error(str(e))
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) with download_dict_lock: download_dict[listener.uid] = MegaDownloadStatus(mega_listener, listener) os.makedirs(path) 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": executor.do(api.getPublicNode, (mega_link,)) node = mega_listener.public_node else: LOGGER.info("Logging into mega folder") 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 listener.onDownloadError(str(mega_listener.error)) gid = ''.join(random.SystemRandom().choices(string.ascii_letters + string.digits, k=8)) mega_listener.setValues(node.getName(), api.getSize(node), gid) executor.do(api.startDownload,(node,path))
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: 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')
def onRequestTemporaryError(self, api, request, error: MegaError): LOGGER.info(f'Mega Request error in {error}') if not self.is_cancelled: self.listener.onDownloadError("RequestTempError: " + error.toString()) self.is_cancelled = True self.error = error.toString() self.continue_event.set()
def connect(self): try: self.conn = psycopg2.connect(DB_URI) self.cur = self.conn.cursor() except psycopg2.DatabaseError as error : LOGGER.error("Error in dbMang : ", error) self.err = True
def update_all_messages(): msg = get_readable_message() msg += f"<b>🖥️ CPU:</b> {psutil.cpu_percent()}%\n" \ f"<b>🚀 RAM:</b> {psutil.virtual_memory().percent}%\n" \ f"<b>📦 DISK:</b> {psutil.disk_usage('/').percent}%\n" 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 'KiB/s' in speedy: dlspeed_bytes += float(speedy.split('K')[0]) * 1024 elif 'MiB/s' 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) msg += f"\n<b>DL:</b>{dlspeed}ps 🔻| <b>UL:</b>{ulspeed}ps 🔺\n" with status_reply_dict_lock: for chat_id in list(status_reply_dict.keys()): if status_reply_dict[ chat_id] and msg != status_reply_dict[chat_id].text: if len(msg) == 0: msg = "Starting DL" try: editMessage(msg, status_reply_dict[chat_id]) except Exception as e: LOGGER.error(str(e)) status_reply_dict[chat_id].text = msg
def onTransferFinish(self, api: MegaApi, transfer: MegaTransfer, error): try: LOGGER.info(f'Transfer finished ({transfer}); Result: {transfer.getFileName()}') if transfer.isFolderTransfer() and transfer.isFinished() or transfer.getFileName() == self.name and not self.is_cancelled: self.listener.onDownloadComplete() self.continue_event.set() except Exception as e: LOGGER.error(e)
def delete_all_messages(): with status_reply_dict_lock: for message in list(status_reply_dict.values()): try: deleteMessage(bot, message) del status_reply_dict[message.chat.id] except Exception as e: LOGGER.error(str(e))
def tar(org_path): tar_path = org_path + ".tar" path = pathlib.PurePath(org_path) LOGGER.info(f'Tar: orig_path: {org_path}, tar_path: {tar_path}') tar = tarfile.open(tar_path, "w") tar.add(org_path, arcname=os.path.basename(org_path)) tar.close() return tar_path
def onUploadComplete(self, link: str, size): with download_dict_lock: msg = f'<b>🗂 文件名称 : </b><code>{download_dict[self.uid].name()}</code>\n<b>📦 总计容量 : </b><code>{size}</code>\n' \ f' \n' \ f'🔅诶,起飞!\n' \ f' \n' \ f'🔅就是飞!\n' buttons = button_build.ButtonMaker() if SHORTENER is not None and SHORTENER_API is not None: surl = requests.get( f'https://{SHORTENER}/api?api={SHORTENER_API}&url={link}&format=text' ).text buttons.buildbutton("🗂 𝐃𝐫𝐢𝐯𝐞 链接 🗂", surl) else: buttons.buildbutton("🗂 𝐃𝐫𝐢𝐯𝐞 链接 🗂", link) LOGGER.info(f'Done Uploading {download_dict[self.uid].name()}') if INDEX_URL is not None: url_path = requests.utils.quote( f'{download_dict[self.uid].name()}') share_url = f'{INDEX_URL}/{url_path}' if os.path.isdir( f'{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}' ): share_url += '/' if SHORTENER is not None and SHORTENER_API is not None: siurl = requests.get( f'https://{SHORTENER}/api?api={SHORTENER_API}&url={share_url}&format=text' ).text buttons.buildbutton("🚀 𝐈𝐧𝐝𝐞𝐱 链接 🚀", siurl) else: buttons.buildbutton("🚀 𝐈𝐧𝐝𝐞𝐱 链接 🚀", share_url) if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None: buttons.buildbutton(f"{BUTTON_THREE_NAME}", f"{BUTTON_THREE_URL}") if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None: buttons.buildbutton(f"{BUTTON_FOUR_NAME}", f"{BUTTON_FOUR_URL}") if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None: buttons.buildbutton(f"{BUTTON_FIVE_NAME}", f"{BUTTON_FIVE_URL}") if self.message.from_user.username: uname = f"@{self.message.from_user.username}" else: uname = f'<a href="tg://user?id={self.message.from_user.id}">{self.message.from_user.first_name}</a>' if uname is not None: msg += f'\n\n<b>👤 上传者 : 👉</b> {uname}\n\n▫️#上传到团队盘 ✓ \n\n🚫 不分享 𝙄𝙣𝙙𝙚𝙭 链接 \n\n✅技术支持 : <b>@wawawame</b>' try: fs_utils.clean_download(download_dict[self.uid].path()) except FileNotFoundError: pass del download_dict[self.uid] count = len(download_dict) sendMarkup(msg, self.bot, self.update, InlineKeyboardMarkup(buttons.build_menu(2))) if count == 0: self.clean() else: update_all_messages()
def onUploadComplete(self, link: str, size): with download_dict_lock: msg = f'<b>🗂 𝗙𝗶𝗹𝗲𝗡𝗮𝗺𝗲 : </b><code>{download_dict[self.uid].name()}</code>\n<b>📦 𝐓𝐨𝐭𝐚𝐥 𝐒𝐢𝐳𝐞 : </b><code>{size}</code>\n' \ f' \n' \ f'🔅MXT MIRROR ZonE\n' \ f' \n' \ f'🔅𝙂𝙧𝙤𝙪𝙥 : @Mxtmirrorgroup\n' buttons = button_build.ButtonMaker() if SHORTENER is not None and SHORTENER_API is not None: surl = requests.get( f'https://{SHORTENER}/api?api={SHORTENER_API}&url={link}&format=text' ).text buttons.buildbutton("🗂 𝐃𝐫𝐢𝐯𝐞 𝐋𝐢𝐧𝐤 🗂", surl) else: buttons.buildbutton("🗂 𝐃𝐫𝐢𝐯𝐞 𝐋𝐢𝐧𝐤 🗂", link) LOGGER.info(f'Done Uploading {download_dict[self.uid].name()}') if INDEX_URL is not None: url_path = requests.utils.quote( f'{download_dict[self.uid].name()}') share_url = f'{INDEX_URL}/{url_path}' if os.path.isdir( f'{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}' ): share_url += '/' if SHORTENER is not None and SHORTENER_API is not None: siurl = requests.get( f'https://{SHORTENER}/api?api={SHORTENER_API}&url={share_url}&format=text' ).text buttons.buildbutton("🚀 𝐈𝐧𝐝𝐞𝐱 𝐋𝐢𝐧𝐤 🚀", siurl) else: buttons.buildbutton("🚀 𝐈𝐧𝐝𝐞𝐱 𝐋𝐢𝐧𝐤 🚀", share_url) if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None: buttons.buildbutton(f"{BUTTON_THREE_NAME}", f"{BUTTON_THREE_URL}") if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None: buttons.buildbutton(f"{BUTTON_FOUR_NAME}", f"{BUTTON_FOUR_URL}") if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None: buttons.buildbutton(f"{BUTTON_FIVE_NAME}", f"{BUTTON_FIVE_URL}") if self.message.from_user.username: uname = f"@{self.message.from_user.username}" else: uname = f'<a href="tg://user?id={self.message.from_user.id}">{self.message.from_user.first_name}</a>' if uname is not None: msg += f'\n\n<b>👤 𝗨𝗽𝗹𝗼𝗮𝗱𝗲𝗿 : 👉</b> {uname}\n\n▫️#Uploaded To Team Drive ✓ \n\n🚫 𝘿𝙤 𝙉𝙤𝙩 𝙎𝙝𝙖𝙧𝙚 𝙄𝙣𝙙𝙚𝙭 𝙇𝙞𝙣𝙠 \n\n✅ 𝗣𝗼𝘄𝗲𝗿𝗲𝗱 𝗕𝘆 : <b>@ZEUTS</b>' try: fs_utils.clean_download(download_dict[self.uid].path()) except FileNotFoundError: pass del download_dict[self.uid] count = len(download_dict) sendMarkup(msg, self.bot, self.update, InlineKeyboardMarkup(buttons.build_menu(2))) if count == 0: self.clean() else: update_all_messages()
def add_download(self, link, path): Path(path).mkdir(parents=True, exist_ok=True) dl = self.__mega_client.addDl(link, path) gid = dl['gid'] info = self.__mega_client.getDownloadInfo(gid) file_name = info['name'] file_size = info['total_length'] self.__onDownloadStart(file_name, file_size, gid) LOGGER.info(f'Started mega download with gid: {gid}')
def exit_clean_up(signal, frame): try: LOGGER.info( "Please wait, while we clean up the downloads and stop running downloads" ) clean_all() sys.exit(0) except KeyboardInterrupt: LOGGER.warning("Force Exiting before the cleanup finishes!") sys.exit(1)
def cancel_download(self): LOGGER.info(f"Cancelling Download: {self.name()}") download = self.aria_download() if download.is_waiting: aria2.remove([download]) self.__listener.onDownloadError("Cancelled by user") return if len(download.followed_by_ids) != 0: downloads = aria2.get_downloads(download.followed_by_ids) aria2.pause(downloads) aria2.pause([download])
def send(msg, bot, update): if len(str(msg)) > 2000: with io.BytesIO(str.encode(msg)) as out_file: out_file.name = "output.txt" bot.send_document( chat_id=update.effective_chat.id, document=out_file) else: LOGGER.info(f"OUT: '{msg}'") bot.send_message( chat_id=update.effective_chat.id, text=f"`{msg}`", parse_mode=ParseMode.MARKDOWN)
def onDownloadError(self, error): error = error.replace('<', ' ') error = error.replace('>', ' ') LOGGER.info(self.update.effective_chat.id) with download_dict_lock: try: download = download_dict[self.uid] del download_dict[self.uid] LOGGER.info(f"Deleting folder: {download.path()}") fs_utils.clean_download(download.path()) LOGGER.info(str(download_dict)) except Exception as e: LOGGER.error(str(e)) pass count = len(download_dict) if self.message.from_user.username: uname = f"@{self.message.from_user.username}" else: uname = f'<a href="tg://user?id={self.message.from_user.id}">{self.message.from_user.first_name}</a>' msg = f"{uname} your download has been stopped due to: {error}" sendMessage(msg, self.bot, self.update) if count == 0: self.clean() else: update_all_messages()
def onTransferTemporaryError(self, api, transfer, error): filen = transfer.getFileName() state = transfer.getState() errStr = error.toString() LOGGER.info(f'Mega download error in file {transfer} {filen}: {error}') if state == 1 or state == 4: # Sometimes MEGA (offical client) can't stream a node either and raises a temp failed error. # Don't break the transfer queue if transfer's in queued (1) or retrying (4) state [causes seg fault] return self.error = errStr if not self.is_cancelled: self.is_cancelled = True self.listener.onDownloadError(f"TransferTempError: {errStr} ({filen})")
def list_drive(update, context): try: search = update.message.text.split(' ', maxsplit=1)[1] LOGGER.info(f"Searching: {search}") reply = sendMessage('Searching..... Please wait!', context.bot, update) gdrive = GoogleDriveHelper(None) msg, button = gdrive.drive_list(search) if button: editMessage(msg, reply, button) else: editMessage('No result found', reply, button) except IndexError: sendMessage('Send a search key along with command', context.bot, update)
def onUploadComplete(self, link: str, size): with download_dict_lock: msg = f'<b>🗂 𝗙𝗶𝗹𝗲𝗡𝗮𝗺𝗲 : </b><code>{download_dict[self.uid].name()}</code>\n<b>𝓣𝓸𝓽𝓪𝓵 𝓢𝓲𝔃𝓮 : </b><code>{size}</code>\n' \ f' \n' \ f'▀▄▀▄▀▄ 𝓂χⓣ 爪𝕀𝕣яỖŕ 𝐙σηe ▄▀▄▀▄▀\n' \ f' \n' \ f'Group : @Zeuts\n' buttons = button_build.ButtonMaker() if SHORTENER is not None and SHORTENER_API is not None: surl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={link}&format=text').text buttons.buildbutton("𝕯𝖗𝖎𝖛𝖊 𝕷𝖎𝖓𝖐", surl) else: buttons.buildbutton("𝕯𝖗𝖎𝖛𝖊 𝕷𝖎𝖓𝖐", link) LOGGER.info(f'Done Uploading {download_dict[self.uid].name()}') if INDEX_URL is not None: url_path = requests.utils.quote(f'{download_dict[self.uid].name()}') share_url = f'{INDEX_URL}/{url_path}' if os.path.isdir(f'{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}'): share_url += '/' if SHORTENER is not None and SHORTENER_API is not None: siurl = requests.get(f'https://{SHORTENER}/api?api={SHORTENER_API}&url={share_url}&format=text').text buttons.buildbutton("𝓲𝓷𝓭𝓮𝔁 𝓵𝓲𝓷𝓴", siurl) else: buttons.buildbutton("𝓲𝓷𝓭𝓮𝔁 𝓵𝓲𝓷𝓴", share_url) if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None: buttons.buildbutton(f"{BUTTON_THREE_NAME}", f"{BUTTON_THREE_URL}") if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None: buttons.buildbutton(f"{BUTTON_FOUR_NAME}", f"{BUTTON_FOUR_URL}") if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None: buttons.buildbutton(f"{BUTTON_FIVE_NAME}", f"{BUTTON_FIVE_URL}") if self.message.from_user.username: uname = f"@{self.message.from_user.username}" else: uname = f'<a href="tg://user?id={self.message.from_user.id}">{self.message.from_user.first_name}</a>' if uname is not None: msg += f'\n\n<b> 𝖀𝖕𝖑𝖔𝖆𝖉𝖊𝖗 </b> {uname}\n\n▫️ 𝖀𝖕𝖑𝖔𝖆𝖉𝖊𝖉 ✓ \n\n 𝓓𝓸𝓷'𝓽 𝓢𝓱𝓪𝓻𝓮 𝓛𝓲𝓷𝓴 \n\n✅ 𝗣𝗼𝘄𝗲𝗿𝗲𝗱 𝗕𝘆 : <b@zeuts</b>' try: fs_utils.clean_download(download_dict[self.uid].path()) except FileNotFoundError: pass del download_dict[self.uid] count = len(download_dict) sendMarkup(msg, self.bot, self.update, InlineKeyboardMarkup(buttons.build_menu(2))) if count == 0: self.clean() else: update_all_messages()
def update_all_messages(): total, used, free = shutil.disk_usage('.') used = get_readable_file_size(used) free = get_readable_file_size(free) msg = get_readable_message() msg += f"<b>🖥️ CPU:</b> {psutil.cpu_percent()}%" \ f"<b>🚀 RAM:</b> {psutil.virtual_memory().percent}%" \ f"<b>📦 DISK:</b> {psutil.disk_usage('/').percent}%" 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 'KiB/s' in speedy: dlspeed_bytes += float(speedy.split('K')[0]) * 1024 elif 'MiB/s' 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) msg += f"\n<b>USED:</b> {used} | <b>FREE:</b> {free}\n<b>DL:</b> {dlspeed}ps 🔻 | <b>UL:</b> {ulspeed}ps 🔺\n" with status_reply_dict_lock: for chat_id in list(status_reply_dict.keys()): if status_reply_dict[ chat_id] and msg != status_reply_dict[chat_id].text: if len(msg) == 0: msg = "Starting DL" try: keyboard = [[ InlineKeyboardButton("🔄 REFRESH 🔄", callback_data=str(ONE)), InlineKeyboardButton("❌ CLOSE ❌", callback_data=str(TWO)), ]] editMessage(msg, status_reply_dict[chat_id], reply_markup=InlineKeyboardMarkup(keyboard)) except Exception as e: LOGGER.error(str(e)) status_reply_dict[chat_id].text = msg
def deletefile(update, context): msg_args = update.message.text.split(None, 1) msg = '' try: link = msg_args[1] LOGGER.info(msg_args[1]) except IndexError: msg = 'Send a link along with command' if msg == '': drive = gdriveTools.GoogleDriveHelper() msg = drive.deletefile(link) LOGGER.info(f"DeleteFileCmd : {msg}") reply_message = sendMessage(msg, context.bot, update) threading.Thread(target=auto_delete_message, args=(context.bot, update.message, reply_message)).start()
def onRequestFinish(self, api, request, error): LOGGER.info('Mega Request finished ({}); Result: {}' .format(request, error)) if str(error).lower() != "no error": self.error = error.copy() return request_type = request.getType() if request_type == MegaRequest.TYPE_LOGIN: api.fetchNodes() elif request_type == MegaRequest.TYPE_GET_PUBLIC_NODE: self.public_node = request.getPublicMegaNode() elif request_type == MegaRequest.TYPE_FETCH_NODES: LOGGER.info("Fetching Root Node.") self.node = api.getRootNode() LOGGER.info(f"Node Name: {self.node.getName()}") if request_type not in self._NO_EVENT_ON or self.node and "cloud drive" not in self.node.getName().lower(): self.continue_event.set()
def deleteMessage(bot, message: Message): try: bot.delete_message(chat_id=message.chat.id, message_id=message.message_id) except Exception as e: LOGGER.error(str(e))
def clean_download(path: str): if os.path.exists(path): LOGGER.info(f"Cleaning download: {path}") shutil.rmtree(path)
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) 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))
def onDownloadComplete(self): with download_dict_lock: LOGGER.info( f"Download completed: {download_dict[self.uid].name()}") download = download_dict[self.uid] name = download.name() size = download.size_raw() m_path = f'{DOWNLOAD_DIR}{self.uid}/{download.name()}' if self.isTar: download.is_archiving = True try: with download_dict_lock: download_dict[self.uid] = TarStatus(name, m_path, size) path = fs_utils.tar(m_path) except FileNotFoundError: LOGGER.info('File to archive not found!') self.onUploadError('Internal error occurred!!') return elif self.extract: download.is_extracting = True try: path = fs_utils.get_base_name(m_path) LOGGER.info(f"Extracting : {name} ") with download_dict_lock: download_dict[self.uid] = ExtractStatus(name, m_path, size) pswd = self.pswd if pswd is not None: archive_result = subprocess.run(["pextract", m_path, pswd]) else: archive_result = subprocess.run(["extract", m_path]) if archive_result.returncode == 0: threading.Thread(target=os.remove, args=(m_path, )).start() LOGGER.info(f"Deleting archive : {m_path}") else: LOGGER.warning( 'Unable to extract archive! Uploading anyway') path = f'{DOWNLOAD_DIR}{self.uid}/{name}' LOGGER.info(f'got path : {path}') except NotSupportedExtractionArchive: LOGGER.info("Not any valid archive, uploading file as it is.") path = f'{DOWNLOAD_DIR}{self.uid}/{name}' else: path = f'{DOWNLOAD_DIR}{self.uid}/{name}' up_name = pathlib.PurePath(path).name up_path = f'{DOWNLOAD_DIR}{self.uid}/{up_name}' if up_name == "None": up_name = "".join(os.listdir(f'{DOWNLOAD_DIR}{self.uid}/')) LOGGER.info(f"Upload Name : {up_name}") drive = gdriveTools.GoogleDriveHelper(up_name, self) size = fs_utils.get_path_size(up_path) upload_status = UploadStatus(drive, size, self) with download_dict_lock: download_dict[self.uid] = upload_status update_all_messages() drive.upload(up_name)