Exemple #1
0
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)
Exemple #2
0
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
Exemple #3
0
 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}')
Exemple #4
0
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])
Exemple #6
0
 def onUploadComplete(self, link: str, size):
     with download_dict_lock:
         msg = f'<b>Filename: </b><code>{download_dict[self.uid].name()}</code>\n<b>Size: </b><code>{size}</code>'
         buttons = button_build.ButtonMaker()
         if SHORTENER is not None and SHORTENER_API is not None:
             surl = requests.get(
                 'https://{}/api?api={}&url={}&format=text'.format(
                     SHORTENER, SHORTENER_API, link)).text
             buttons.buildbutton("Drive Link", surl)
         else:
             buttons.buildbutton("Drive Link", link)
         LOGGER.info(f'Done Uploading {download_dict[self.uid].name()}')
         if INDEX_URL is not None:
             url_path = requests.utils.quote(
                 f'{download_dict[self.uid].name()}')
             share_url = f'{INDEX_URL}/{url_path}'
             if os.path.isdir(
                     f'{DOWNLOAD_DIR}/{self.uid}/{download_dict[self.uid].name()}'
             ):
                 share_url += '/'
             if SHORTENER is not None and SHORTENER_API is not None:
                 siurl = requests.get(
                     'https://{}/api?api={}&url={}&format=text'.format(
                         SHORTENER, SHORTENER_API, share_url)).text
                 buttons.buildbutton("Index Link", siurl)
             else:
                 buttons.buildbutton("Index Link", share_url)
         if BUTTON_THREE_NAME is not None and BUTTON_THREE_URL is not None:
             buttons.buildbutton(f"{BUTTON_THREE_NAME}",
                                 f"{BUTTON_THREE_URL}")
         if BUTTON_FOUR_NAME is not None and BUTTON_FOUR_URL is not None:
             buttons.buildbutton(f"{BUTTON_FOUR_NAME}",
                                 f"{BUTTON_FOUR_URL}")
         if BUTTON_FIVE_NAME is not None and BUTTON_FIVE_URL is not None:
             buttons.buildbutton(f"{BUTTON_FIVE_NAME}",
                                 f"{BUTTON_FIVE_URL}")
         if self.message.from_user.username:
             uname = f"@{self.message.from_user.username}"
         else:
             uname = f'<a href="tg://user?id={self.message.from_user.id}">{self.message.from_user.first_name}</a>'
         if uname is not None:
             msg += f'\n\ncc: {uname}'
         try:
             fs_utils.clean_download(download_dict[self.uid].path())
         except FileNotFoundError:
             pass
         del download_dict[self.uid]
         count = len(download_dict)
     sendMarkup(msg, self.bot, self.update,
                InlineKeyboardMarkup(buttons.build_menu(2)))
     if count == 0:
         self.clean()
     else:
         update_all_messages()
Exemple #7
0
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)
Exemple #8
0
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"this is msg : {msg}")
    reply_message = sendMessage(msg, context.bot, update)

    threading.Thread(target=auto_delete_message, args=(context.bot, update.message, reply_message)).start()
Exemple #9
0
def list_drive(update, context):
    if update.message.text == f'/{BotCommands.ListCommand}':
        sendMessage(
            f'Send a search key along with {BotCommands.ListCommand} command',
            context.bot, update)
    else:
        search = update.message.text.split(' ', maxsplit=1)[1]
        LOGGER.info(f"Searching: '{search}'...")
        reply = sendMessage('Searching.....\nPlease Wait!', context.bot,
                            update)
        gdrive = GoogleDriveHelper(None)
        msg, button = gdrive.drive_list(search)
        if msg:
            if button:
                editMessage(msg, reply, button)
            else:
                editMessage(msg, reply)
        else:
            editMessage('No results found', reply)
Exemple #10
0
 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()
Exemple #11
0
    def add_download(self, message, path):
        _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 download:
                self.__onDownloadStart(media.file_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')
Exemple #12
0
 def cancel_download(self):
     LOGGER.info(f'Cancelling download on user request: {self.gid}')
     self.__is_cancelled = True
Exemple #13
0
def clean_download(path: str):
    if os.path.exists(path):
        LOGGER.info(f"Cleaning download: {path}")
        shutil.rmtree(path)
Exemple #14
0
    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)
Exemple #15
0
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)
        sendStatusMessage(update, bot)
    if len(Interval) == 0:
        Interval.append(
            setInterval(DOWNLOAD_STATUS_UPDATE_INTERVAL, update_all_messages))
Exemple #16
0
def log_input(update):
    user = update.effective_user.id
    chat = update.effective_chat.id
    LOGGER.info(
        f"IN: {update.effective_message.text} (user={user}, chat={chat})")
Exemple #17
0
 def cancel_download(self):
     LOGGER.info(f'Cancelling download on user request: {self.gid}')
     self.__mega_client.cancelDl(self.gid)