Exemple #1
0
async def upload_to_tg(message: Message):
    """ upload to telegram """
    path_ = message.filtered_input_str
    if not path_:
        await message.err("Input not foud!")
        return
    is_path_url = is_url(path_)
    del_path = False
    if is_path_url:
        del_path = True
        try:
            path_, _ = await url_download(message, path_)
        except ProcessCanceled:
            await message.canceled()
            return
        except Exception as e_e:  # pylint: disable=broad-except
            await message.err(str(e_e))
            return
    if "|" in path_:
        path_, file_name = path_.split("|")
        path_ = path_.strip()
        if os.path.isfile(path_):
            new_path = os.path.join(Config.DOWN_PATH, file_name.strip())
            os.rename(path_, new_path)
            path_ = new_path
    try:
        string = Path(path_)
    except IndexError:
        await message.err("wrong syntax")
    else:
        await message.delete()
        with message.cancel_callback():
            await upload_path(message, string, del_path)
Exemple #2
0
async def tg_download(message: Message,
                      to_download: Message,
                      from_url: bool = False) -> Tuple[str, int]:
    """ download from tg file """
    await message.edit("`Downloading From TG...`")
    start_t = datetime.now()
    custom_file_name = Config.DOWN_PATH
    if message.filtered_input_str and not from_url:
        custom_file_name = os.path.join(Config.DOWN_PATH,
                                        message.filtered_input_str.strip())
    elif "|" in message.filtered_input_str:
        _, c_file_name = message.filtered_input_str.split("|", maxsplit=1)
        if c_file_name:
            custom_file_name = os.path.join(Config.DOWN_PATH,
                                            c_file_name.strip())
    with message.cancel_callback():
        dl_loc = await message.client.download_media(
            message=to_download,
            file_name=custom_file_name,
            progress=progress,
            progress_args=(message, "trying to download"))
    if message.process_is_canceled:
        raise ProcessCanceled
    if not isinstance(dl_loc, str):
        raise TypeError("File Corrupted!")
    dl_loc = os.path.relpath(dl_loc)
    return dl_loc, (datetime.now() - start_t).seconds
Exemple #3
0
async def combine_(message: Message) -> None:
    """ combine split files """
    file_path = message.input_str
    if not file_path:
        await message.err("missing file path!")
        return
    if not isfile(file_path):
        await message.err("file path not exists!")
        return
    _, ext = splitext(basename(file_path))
    if not ext.lstrip('.').isdigit():
        await message.err("unsupported file!")
        return
    await message.edit("`processing...`")
    start_t = datetime.now()
    c_obj = SCLib(file_path)
    c_obj.combine()
    tmp = \
        "__Combining file path...__\n" + \
        "```{}({}%)```\n" + \
        "**File Path** : `{}`\n" + \
        "**Dest** : `{}`\n" + \
        "**Completed** : `{}`\n" + \
        "**Total** : `{}`\n" + \
        "**Speed** : `{}/s`\n" + \
        "**ETA** : `{}`\n" + \
        "**Completed Files** : `{}/{}`"

    async def _worker():
        while not c_obj.finished:
            await message.edit(
                tmp.format(c_obj.progress, c_obj.percentage, file_path,
                           c_obj.final_file_path, humanbytes(c_obj.completed),
                           humanbytes(c_obj.total), humanbytes(c_obj.speed),
                           c_obj.eta, c_obj.completed_files,
                           c_obj.total_files))
            await sleep(Config.EDIT_SLEEP_TIMEOUT)

    def _on_cancel():
        c_obj.cancel()
        task.cancel()

    task = asyncio.create_task(_worker())
    with message.cancel_callback(_on_cancel):
        try:
            await task
        except asyncio.CancelledError:
            await message.canceled()
            return

    if c_obj.output:
        await message.err(c_obj.output, show_help=False)
    else:
        end_t = datetime.now()
        m_s = (end_t - start_t).seconds
        await message.edit(
            f"**combined** `{file_path}` into `{c_obj.final_file_path}` "
            f"in `{m_s}` seconds.",
            log=__name__)
Exemple #4
0
async def split_(message: Message) -> None:
    """ split files """
    split_size = int(message.matches[0].group(1))
    file_path = str(message.matches[0].group(2))
    if not file_path:
        await message.err("missing file path!")
        return
    if not isfile(file_path):
        await message.err("file path not exists!")
        return
    await message.edit("`processing...`")
    start_t = datetime.now()
    s_obj = SCLib(file_path)
    s_obj.split(split_size)
    tmp = \
        "__Splitting file path...__\n" + \
        "```{}({}%)```\n" + \
        "**File Path** : `{}`\n" + \
        "**Dest** : `{}`\n" + \
        "**Completed** : `{}`\n" + \
        "**Total** : `{}`\n" + \
        "**Speed** : `{}/s`\n" + \
        "**ETA** : `{}`\n" + \
        "**Completed Files** : `{}/{}`"

    async def _worker():
        while not s_obj.finished:
            await message.edit(tmp.format(s_obj.progress,
                                          s_obj.percentage,
                                          file_path,
                                          s_obj.final_file_path,
                                          humanbytes(s_obj.completed),
                                          humanbytes(s_obj.total),
                                          humanbytes(s_obj.speed),
                                          s_obj.eta,
                                          s_obj.completed_files,
                                          s_obj.total_files))
            await sleep(Config.EDIT_SLEEP_TIMEOUT)

    def _on_cancel():
        s_obj.cancel()
        task.cancel()

    task = asyncio.create_task(_worker())
    with message.cancel_callback(_on_cancel):
        try:
            await task
        except asyncio.CancelledError:
            await message.canceled()
            return

    if s_obj.output:
        await message.err(s_obj.output, show_help=False)
    else:
        end_t = datetime.now()
        m_s = (end_t - start_t).seconds
        await message.edit(
            f"**split** `{file_path}` into `{s_obj.final_file_path}` "
            f"in `{m_s}` seconds.", log=__name__)
Exemple #5
0
async def term_(message: Message):
    """ run commands in shell (terminal with live update) """
    cmd = await init_func(message)
    if cmd is None:
        return

    await message.edit("`Executing terminal ...`")
    try:
        parsed_cmd = parse_py_template(cmd, message)
    except Exception as e:  # pylint: disable=broad-except
        await message.err(str(e))
        await CHANNEL.log(f"**Exception**: {type(e).__name__}\n**Message**: " +
                          str(e))
        return
    try:
        t_obj = await Term.execute(parsed_cmd)  # type: Term
    except Exception as t_e:  # pylint: disable=broad-except
        await message.err(str(t_e))
        return

    cur_user = getuser()
    try:
        uid = geteuid()
    except ImportError:
        uid = 1
    prefix = f"<b>{cur_user}:~#</b>" if uid == 0 else f"<b>{cur_user}:~$</b>"
    output = f"{prefix} <pre>{cmd}</pre>\n"

    async def _worker():
        await t_obj.wait()
        while not t_obj.finished:
            await message.edit(f"{output}<pre>{await t_obj.read_line()}</pre>",
                               parse_mode='html')
            try:
                await asyncio.wait_for(t_obj.finish_listener,
                                       Config.EDIT_SLEEP_TIMEOUT)
            except asyncio.TimeoutError:
                pass

    def _on_cancel():
        t_obj.cancel()
        task.cancel()

    task = asyncio.create_task(_worker())
    with message.cancel_callback(_on_cancel):
        try:
            await task
        except asyncio.CancelledError:
            await message.canceled(reply=True)
            return

    out_data = f"{output}<pre>{await t_obj.get_output()}</pre>\n{prefix}"
    await message.edit_or_send_as_file(out_data,
                                       parse_mode='html',
                                       filename="term.txt",
                                       caption=cmd)
Exemple #6
0
async def _handle_message(message: Message) -> None:
    try:
        dl_loc, _ = await tg_download(message, message.reply_to_message)
    except ProcessCanceled:
        await message.canceled()
    except Exception as e_e:  # pylint: disable=broad-except
        await message.err(str(e_e))
    else:
        await message.delete()
        with message.cancel_callback():
            await upload(message, Path(dl_loc), True)
Exemple #7
0
async def unpack_(message: Message) -> None:
    """ unpack packed file """
    file_path = message.input_str
    if not file_path:
        await message.err("missing file path!")
        return
    if not exists(file_path):
        await message.err("file path not exists!")
        return
    if not PackLib.is_supported(file_path):
        await message.err("unsupported file type!")
        return
    await message.edit("`processing...`")
    start_t = datetime.now()
    p_obj = PackLib(file_path)
    p_obj.unpack_path()
    tmp = \
        "__UnPacking file path...__\n" + \
        "```{}({}%)```\n" + \
        "**File Path** : `{}`\n" + \
        "**Dest** : `{}`\n" + \
        "**Completed** : `{}/{}`"

    async def _worker():
        while not p_obj.finished:
            await message.edit(tmp.format(p_obj.progress,
                                          p_obj.percentage,
                                          file_path,
                                          p_obj.final_file_path,
                                          p_obj.completed_files,
                                          p_obj.total_files))
            await sleep(Config.EDIT_SLEEP_TIMEOUT)

    def _on_cancel():
        p_obj.cancel()
        task.cancel()

    task = asyncio.create_task(_worker())
    with message.cancel_callback(_on_cancel):
        try:
            await task
        except asyncio.CancelledError:
            await message.canceled()
            return

    if p_obj.output:
        await message.err(p_obj.output, show_help=False)
    else:
        end_t = datetime.now()
        m_s = (end_t - start_t).seconds
        await message.edit(
            f"**unpacked** `{file_path}` into `{p_obj.final_file_path}` "
            f"in `{m_s}` seconds.", log=__name__)
Exemple #8
0
async def url_download(message: Message, url: str) -> Tuple[str, int]:
    """ download from link """
    await message.edit("`Downloading From URL...`")
    start_t = datetime.now()
    custom_file_name = unquote_plus(os.path.basename(url))
    if "|" in url:
        url, c_file_name = url.split("|", maxsplit=1)
        url = url.strip()
        if c_file_name:
            custom_file_name = c_file_name.strip()
    dl_loc = os.path.join(Config.DOWN_PATH, custom_file_name)
    downloader = SmartDL(url, dl_loc, progress_bar=False)
    downloader.start(blocking=False)
    with message.cancel_callback(downloader.stop):
        while not downloader.isFinished():
            total_length = downloader.filesize if downloader.filesize else 0
            downloaded = downloader.get_dl_size()
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed(human=True)
            estimated_total_time = downloader.get_eta(human=True)
            progress_str = \
                "__{}__\n" + \
                "```[{}{}]```\n" + \
                "**Progress** : `{}%`\n" + \
                "**URL** : `{}`\n" + \
                "**FILENAME** : `{}`\n" + \
                "**Completed** : `{}`\n" + \
                "**Total** : `{}`\n" + \
                "**Speed** : `{}`\n" + \
                "**ETA** : `{}`"
            progress_str = progress_str.format(
                "trying to download", ''.join(
                    (Config.FINISHED_PROGRESS_STR
                     for _ in range(math.floor(percentage / 5)))), ''.join(
                         (Config.UNFINISHED_PROGRESS_STR
                          for _ in range(20 - math.floor(percentage / 5)))),
                round(percentage, 2), url, custom_file_name,
                humanbytes(downloaded), humanbytes(total_length), speed,
                estimated_total_time)
            await message.edit(progress_str, disable_web_page_preview=True)
            await asyncio.sleep(Config.EDIT_SLEEP_TIMEOUT)
    if message.process_is_canceled:
        raise ProcessCanceled
    return dl_loc, (datetime.now() - start_t).seconds
Exemple #9
0
async def term_(message: Message):
    """ run commands in shell (terminal with live update) """
    await message.edit("`Executing terminal ...`")
    cmd = message.filtered_input_str
    as_raw = '-r' in message.flags

    try:
        parsed_cmd = parse_py_template(cmd, message)
    except Exception as e:  # pylint: disable=broad-except
        await message.err(str(e))
        await CHANNEL.log(f"**Exception**: {type(e).__name__}\n**Message**: " +
                          str(e))
        return
    try:
        t_obj = await Term.execute(parsed_cmd)  # type: Term
    except Exception as t_e:  # pylint: disable=broad-except
        await message.err(str(t_e))
        return

    cur_user = getuser()
    uid = geteuid()

    prefix = f"<b>{cur_user}:~#</b>" if uid == 0 else f"<b>{cur_user}:~$</b>"
    output = f"{prefix} <pre>{cmd}</pre>\n"

    with message.cancel_callback(t_obj.cancel):
        await t_obj.init()
        while not t_obj.finished:
            await message.edit(f"{output}<pre>{t_obj.line}</pre>",
                               parse_mode='html')
            await t_obj.wait(config.Dynamic.EDIT_SLEEP_TIMEOUT)
        if t_obj.cancelled:
            await message.canceled(reply=True)
            return

    out_data = f"{output}<pre>{t_obj.output}</pre>\n{prefix}"
    await message.edit_or_send_as_file(out_data,
                                       as_raw=as_raw,
                                       parse_mode='html',
                                       filename="term.txt",
                                       caption=cmd)
Exemple #10
0
async def tg_download(message: Message,
                      to_download: Message,
                      from_url: bool = False) -> Tuple[str, int]:
    """ download from tg file """
    if not to_download.media:
        dl_loc, mite = [], 0
        ets = extract_entities(
            to_download,
            [enums.MessageEntityType.URL, enums.MessageEntityType.TEXT_LINK])
        if len(ets) == 0:
            raise Exception("nothing found to download")
        for uarl in ets:
            _dl_loc, b_ = await url_download(message, uarl)
            dl_loc.append(_dl_loc)
            mite += b_
        return dumps(dl_loc), mite
    await message.edit("`Downloading From TG...`")
    start_t = datetime.now()
    custom_file_name = config.Dynamic.DOWN_PATH
    if message.filtered_input_str and not from_url:
        custom_file_name = os.path.join(config.Dynamic.DOWN_PATH,
                                        message.filtered_input_str.strip())
    elif "|" in message.filtered_input_str:
        _, c_file_name = message.filtered_input_str.split("|", maxsplit=1)
        if c_file_name:
            custom_file_name = os.path.join(config.Dynamic.DOWN_PATH,
                                            c_file_name.strip())
    with message.cancel_callback():
        dl_loc = await message.client.download_media(
            message=to_download,
            file_name=custom_file_name,
            progress=progress,
            progress_args=(message, "trying to download"))
    if message.process_is_canceled:
        raise ProcessCanceled
    if not isinstance(dl_loc, str):
        raise TypeError("File Corrupted!")
    dl_loc = os.path.relpath(dl_loc)
    return dl_loc, (datetime.now() - start_t).seconds
Exemple #11
0
async def url_download(message: Message, url: str) -> Tuple[str, int]:
    """ download from link """
    pattern = r"^(?:(?:https|tg):\/\/)?(?:www\.)?(?:t\.me\/|openmessage\?)(?:(?:c\/(\d+))|(\w+)|(?:user_id\=(\d+)))(?:\/|&message_id\=)(\d+)(\?single)?$"  # noqa
    # group 1: private supergroup id, group 2: chat username,
    # group 3: private group/chat id, group 4: message id
    # group 5: check for download single media from media group
    match = re.search(pattern, url.split('|', 1)[0].strip())
    if match:
        chat_id = None
        msg_id = int(match.group(4))
        if match.group(1):
            chat_id = int("-100" + match.group(1))
        elif match.group(2):
            chat_id = match.group(2)
        elif match.group(3):
            chat_id = int(match.group(3))
        if chat_id and msg_id:
            resource = await message.client.get_messages(chat_id, msg_id)
            if resource.media_group_id and not bool(match.group(5)):
                output = await handle_download(message, resource, True)
            elif resource.media:
                output = await tg_download(message, resource, True)
            else:
                raise Exception("given tg link doesn't have any media")
            return output
        raise Exception("invalid telegram message link!")
    await message.edit("`Downloading From URL...`")
    start_t = datetime.now()
    custom_file_name = unquote_plus(os.path.basename(url))
    if "|" in url:
        url, c_file_name = url.split("|", maxsplit=1)
        url = url.strip()
        if c_file_name:
            custom_file_name = c_file_name.strip()
    dl_loc = os.path.join(config.Dynamic.DOWN_PATH, custom_file_name)
    downloader = SmartDL(url, dl_loc, progress_bar=False)
    downloader.start(blocking=False)
    with message.cancel_callback(downloader.stop):
        while not downloader.isFinished():
            total_length = downloader.filesize if downloader.filesize else 0
            downloaded = downloader.get_dl_size()
            percentage = downloader.get_progress() * 100
            speed = downloader.get_speed(human=True)
            estimated_total_time = downloader.get_eta(human=True)
            progress_str = \
                "__{}__\n" + \
                "```[{}{}]```\n" + \
                "**Progress** : `{}%`\n" + \
                "**URL** : `{}`\n" + \
                "**FILENAME** : `{}`\n" + \
                "**Completed** : `{}`\n" + \
                "**Total** : `{}`\n" + \
                "**Speed** : `{}`\n" + \
                "**ETA** : `{}`"
            progress_str = progress_str.format(
                "trying to download", ''.join(
                    (config.FINISHED_PROGRESS_STR
                     for _ in range(math.floor(percentage / 5)))), ''.join(
                         (config.UNFINISHED_PROGRESS_STR
                          for _ in range(20 - math.floor(percentage / 5)))),
                round(percentage, 2), url, custom_file_name,
                humanbytes(downloaded), humanbytes(total_length), speed,
                estimated_total_time)
            await message.edit(progress_str, disable_web_page_preview=True)
            await asyncio.sleep(config.Dynamic.EDIT_SLEEP_TIMEOUT)
    if message.process_is_canceled:
        raise ProcessCanceled
    return dl_loc, (datetime.now() - start_t).seconds