コード例 #1
0
async def incoming_purge_message_f(client, message):
    """/purge command"""
    print(message.client)
    i_m_sefg2 = await message.reply_text("Purging...", quote=True)
    if await AdminCheck(client, message.chat.id, message.from_user.id):
        aria_i_p = await aria_start()
        # Show All Downloads
        downloads = aria_i_p.get_downloads()
        for download in downloads:
            LOGGER.info(download.remove(force=True))
    await i_m_sefg2.delete()
コード例 #2
0
async def down_load_media_f(client, message):
    user_command = message.command[0]
    user_id = message.from_user.id
    LOGGER.info(user_id)
    mess_age = await message.reply_text(
        "Is it really a Telegram Media 🤔!\nJust to make sure 🤷‍♂️ \nIf yes, then wait a few minutes",
        quote=True)
    if not os.path.isdir(DOWNLOAD_LOCATION):
        os.makedirs(DOWNLOAD_LOCATION)
    if message.reply_to_message is not None:
        start_t = datetime.now()
        download_location = str(Path().resolve()) + "/"
        c_time = time.time()
        prog = Progress(user_id, client, mess_age)
        try:
            the_real_download_location = await client.download_media(
                message=message.reply_to_message,
                file_name=download_location,
                progress=prog.progress_for_pyrogram,
                progress_args=("trying to download", c_time),
            )
        except Exception as g_e:
            await mess_age.edit(str(g_e))
            LOGGER.error(g_e)
            return
        end_t = datetime.now()
        ms = (end_t - start_t).seconds
        LOGGER.info(the_real_download_location)
        await asyncio.sleep(10)
        if the_real_download_location:
            await mess_age.edit_text(
                f"Downloaded to <code>{the_real_download_location}</code> in <u>{ms}</u> seconds"
            )
        else:
            await mess_age.edit_text(
                "😔 Download Cancelled or some error happened")
            return
        the_real_download_location_g = the_real_download_location
        if user_command == TELEGRAM_LEECH_UNZIP_COMMAND.lower():
            try:
                check_ifi_file = get_base_name(the_real_download_location)
                file_up = await unzip_me(the_real_download_location)
                if os.path.exists(check_ifi_file):
                    the_real_download_location_g = file_up
            except Exception as ge:
                LOGGER.info(ge)
                LOGGER.info(
                    f"Unable to extract {os.path.basename(the_real_download_location)}, Uploading the same file"
                )
        await upload_to_gdrive(the_real_download_location_g, mess_age, message,
                               user_id)
    else:
        await mess_age.edit_text(
            "Reply to a Telegram Media, to upload to the Cloud Drive.")
コード例 #3
0
async def fake_etairporpa_call(aria_instance, incoming_link, c_file_name,
                               sent_message_to_update_tg_p,
                               r_clone_header_xedni):
    # TODO: duplicate code -_-
    if incoming_link.lower().startswith("magnet:"):
        sagtus, err_message = add_magnet(aria_instance, incoming_link,
                                         c_file_name)
    elif incoming_link.lower().endswith(".torrent"):
        sagtus, err_message = add_torrent(aria_instance, incoming_link)
    else:
        sagtus, err_message = add_url(aria_instance, incoming_link,
                                      c_file_name)
    if not sagtus:
        return sagtus, err_message
    LOGGER.info(err_message)
    # https://stackoverflow.com/a/58213653/4723940
    await check_progress_for_dl(aria_instance, err_message,
                                sent_message_to_update_tg_p, None)
    if incoming_link.startswith("magnet:"):
        #
        err_message = await check_metadata(aria_instance, err_message)
        #
        await asyncio.sleep(1)
        if err_message is not None:
            await check_progress_for_dl(aria_instance, err_message,
                                        sent_message_to_update_tg_p, None)
        else:
            return False, "can't get metadata \n\n#stopped"
    await asyncio.sleep(1)
    file = aria_instance.get_download(err_message)
    to_upload_file = file.name
    # -_-
    r_clone_conf_file = await get_r_clone_config(
        R_CLONE_CONF_URI, sent_message_to_update_tg_p._client)
    if r_clone_conf_file is not None:  # how? even :\
        config = configparser.ConfigParser()
        config.read(r_clone_conf_file)
        remote_names = config.sections()
        try:
            required_remote = remote_names[r_clone_header_xedni]
        except IndexError:
            return False, "maybe a bug, but index seems not valid"
        remote_file_id = await copy_via_rclone(
            to_upload_file,
            required_remote,
            R_CLONE_DEST,  # rclone destination folder
            r_clone_conf_file)
        # temporary hard coded id for Google Drive only. :\
        # TODO
        await sent_message_to_update_tg_p.reply_text(
            "files might be uploaded in the desired remote "
            "please check Logs for any errors"
            f"\n\nhttps://drive.google.com/open?id={remote_file_id}")
        return True, None
コード例 #4
0
async def fake_etairporpa_call(
    aria_instance,
    incoming_link,
    c_file_name,
    sent_message_to_update_tg_p,
    r_clone_header_xedni,
):
    # TODO: duplicate code -_-
    if incoming_link.lower().startswith("magnet:"):
        sagtus, err_message = add_magnet(aria_instance, incoming_link,
                                         c_file_name)
    elif os.path.isfile(incoming_link) and incoming_link.lower().endswith(
            ".torrent"):
        sagtus, err_message = add_torrent(aria_instance, incoming_link)
    else:
        sagtus, err_message = add_url(aria_instance, incoming_link,
                                      c_file_name)
    if not sagtus:
        return sagtus, err_message
    LOGGER.info(err_message)
    # https://stackoverflow.com/a/58213653/4723940
    await check_progress_for_dl(aria_instance, err_message,
                                sent_message_to_update_tg_p, None)
    has_metadata = aria_instance.client.tell_status(err_message,
                                                    ["followedBy"])
    if has_metadata:
        err_message = has_metadata["followedBy"][0]
        await check_progress_for_dl(aria_instance, err_message,
                                    sent_message_to_update_tg_p, None)
    await asyncio.sleep(1)
    file = aria_instance.get_download(err_message)
    to_upload_file = file.name
    # -_-
    r_clone_conf_file = await get_r_clone_config(
        Config.R_CLONE_CONF_URI, sent_message_to_update_tg_p._client)
    if r_clone_conf_file is not None:  # how? even :\
        config = configparser.ConfigParser()
        config.read(r_clone_conf_file)
        remote_names = config.sections()
        try:
            required_remote = remote_names[r_clone_header_xedni]
        except IndexError:
            return False, "maybe a bug, but index seems not valid"
        remote_file_link = await copy_via_rclone(
            to_upload_file,
            required_remote,
            Config.R_CLONE_DEST,  # rclone destination folder
            r_clone_conf_file,
        )
        await sent_message_to_update_tg_p.reply_text(
            "files might be uploaded in the desired remote "
            "please check Logs for any errors"
            f"\n\n{remote_file_link}")
        return True, None
コード例 #5
0
async def rename_tg_file(client, message):
    usr_id = message.from_user.id
    if not message.reply_to_message:
        await message.reply("😔 No downloading source provided 🙄", quote=True)
        return
    if len(message.command) > 1:
        new_name = (
            str(Path().resolve()) + "/" + message.text.split(" ", maxsplit=1)[1].strip()
        )
        file = await download_tg(client, message)
        try:
            if file:
                os.rename(file, new_name)
            else:
                return
        except Exception as g_g:
            await message.reply_text("g_g")
        response = {}
        final_response = await upload_to_tg(message, new_name, usr_id, response)
        LOGGER.info(final_response)
        try:
            message_to_send = ""
            for key_f_res_se in final_response:
                local_file_name = key_f_res_se
                message_id = final_response[key_f_res_se]
                channel_id = str(message.chat.id)[4:]
                private_link = f"https://t.me/c/{channel_id}/{message_id}"
                message_to_send += "👉 <a href='"
                message_to_send += private_link
                message_to_send += "'>"
                message_to_send += local_file_name
                message_to_send += "</a>"
                message_to_send += "\n"
            if message_to_send != "":
                mention_req_user = (
                    f"<a href='tg://user?id={usr_id}'>Your Requested Files</a>\n\n"
                )
                message_to_send = mention_req_user + message_to_send
                message_to_send = message_to_send + "\n\n" + "#uploads"
            else:
                message_to_send = "<i>FAILED</i> to upload files. 😞😞"
            await message.reply_text(
                text=message_to_send, quote=True, disable_web_page_preview=True
            )
        except Exception as pe:
            LOGGER.info(pe)

    else:
        await message.reply_text(
            "😔 Provide new name of the file with extension 😐", quote=True
        )
コード例 #6
0
async def incoming_youtube_dl_f(client, message):
    """ /ytdl command """
    g_id = message.from_user.id
    credit = await message.reply_text(
        f"💀 Downloading for you <a href='tg://user?id={g_id}'>🤕</a>",
        parse_mode="html")
    i_m_sefg = await message.reply_text("processing", quote=True)
    # LOGGER.info(message)
    # extract link from message
    dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link(
        message.reply_to_message, "YTDL")
    LOGGER.info(dl_url)
    # if len(message.command) > 1:
    # if message.command[1] == "gdrive":
    # with open('blame_my_knowledge.txt', 'w+') as gg:
    # gg.write("I am noob and don't know what to do that's why I have did this")
    LOGGER.info(cf_name)
    if dl_url is not None:
        await i_m_sefg.edit_text("extracting links")
        current_user_id = message.from_user.id
        # create an unique directory
        user_working_dir = os.path.join(DOWNLOAD_LOCATION,
                                        str(current_user_id))
        # create download directory, if not exist
        if not os.path.isdir(user_working_dir):
            os.makedirs(user_working_dir)
        # list the formats, and display in button markup formats
        thumb_image, text_message, reply_markup = await extract_youtube_dl_formats(
            dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word,
            user_working_dir)
        if thumb_image is not None:
            print(thumb_image)
            req = requests.get(f"{thumb_image}")
            gau_tam = f"{current_user_id}.jpg"
            open(gau_tam, "wb").write(req.content)
            await message.reply_photo(
                # text_message,
                photo=gau_tam,
                quote=True,
                caption=text_message,
                reply_markup=reply_markup,
            )
            await i_m_sefg.delete()
        else:
            await i_m_sefg.edit_text(text=text_message,
                                     reply_markup=reply_markup)
    else:
        await i_m_sefg.edit_text(
            "**FCUK**! wat have you entered. \nPlease read /help \n"
            f"<b>API Error</b>: {cf_name}")
コード例 #7
0
async def upload_document_f(client, message):
    imsegd = await message.reply_text(
        Loilacaztion.PROCESSING
    )
    if " " in message.text:
        recvd_command, local_file_name = message.text.split(" ", 1)
        recvd_response = await upload_to_tg(
            imsegd,
            local_file_name,
            message.from_user.id,
            {}
        )
        LOGGER.info(recvd_response)
    await imsegd.delete()
コード例 #8
0
async def copy_via_rclone(src: str, remote_name: str, remote_dir: str,
                          conf_file: str):
    if os.path.isdir(src):
        remote_dir = f"{remote_dir}/{src}"
    command_to_exec = [
        "rclone",
        "move",
        src,
        f"{remote_name}:{remote_dir}",
        f"--config={conf_file}",
        "--fast-list",
        "--transfers",
        "18",
        "--checkers",
        "10",
        "--drive-chunk-size",
        "64M",
    ]
    LOGGER.info(command_to_exec)
    t_response, e_response = await run_command(command_to_exec)
    # Wait for the subprocess to finish
    LOGGER.info(e_response)
    LOGGER.info(t_response)
    # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239
    remote_file_link = await r_clone_extract_link_s(re.escape(src),
                                                    remote_name, remote_dir,
                                                    conf_file)
    LOGGER.info(remote_file_link)
    return remote_file_link
コード例 #9
0
async def cancel_message_f(client, message):
    if len(message.command) > 1:
        # /cancel command
        i_m_s_e_g = await message.reply_text("checking..?", quote=True)
        aria_i_p = await aria_start()
        g_id = message.command[1].strip()
        LOGGER.info(g_id)
        try:
            downloads = aria_i_p.get_download(g_id)
            LOGGER.info(downloads)
            LOGGER.info(downloads.remove(force=True))
            await i_m_s_e_g.edit_text("Leech Cancelled")
        except Exception as e:
            await i_m_s_e_g.edit_text("<i>FAILED</i>\n\n" + str(e) +
                                      "\n#error")
    elif message.reply_to_message != None:
        if not isinstance(DB_HOST_URL, bool):
            res = dbh.markCancel(message.reply_to_message.chat.id,
                                 message.reply_to_message.message_id)
            LOGGER.info("Canceling the upload {}\n{}".format(
                message.reply_to_message.chat.id,
                message.reply_to_message.message_id))
            if res:
                await message.reply_to_message.edit_text(
                    text="{} - cancellation requested.".format(
                        message.reply_to_message.text))
            else:
                await message.reply_text(
                    "Cancel received no download to cancel")
        else:
            await message.reply_text(
                "Please create a database for Heroku or specify DB_HOST_URL if legacy hosted."
            )
    else:
        await message.delete()
コード例 #10
0
async def status_message_f(client, message):
    aria_i_p = await aria_start()
    # Show All Downloads
    downloads = aria_i_p.get_downloads()
    #
    #
    msg = ""
    for download in downloads:
        downloading_dir_name = "NA"
        try:
            downloading_dir_name = str(download.name)
        except:
            pass
        if download.status == "active":
            total_length_size = str(download.total_length_string())
            progress_length = str(download.completed_length_string())
            down_speed_string = str(download.download_speed_string())
            up_speed_string = str(download.upload_speed_string())
            download_current_status = str(download.status)
            e_t_a = str(download.eta_string())
            msg += f"<b>Name</b>: <u>{downloading_dir_name}</u> \n<b>Speed</b>: D: {down_speed_string} U: {up_speed_string} \n<b>Progress</b>: {progress_length} of {total_length_size} \n<b>ETA</b>: {e_t_a}\n\n"
        # LOGGER.info(msg)

        if msg == "":
            msg = "­ЪциРђЇРЎѓ№ИЈ No Active, Queued or Paused TORRENTs"

    hr, mi, se = up_time(time.time() - BOT_START_TIME)
    total, used, free = shutil.disk_usage(".")
    total = humanbytes(total)
    used = humanbytes(used)
    free = humanbytes(free)

    ms_g = (f"<b>Bot Uptime</b>: {hr}:{mi}:{se}\n"
            f"<b>Used</b>: {used}\n"
            f"<b>Free</b>: {free}\n"
            f"<b>Total disk space</b>: {total}\n")
    # LOGGER.info(ms_g)

    msg = ms_g + "\n" + msg
    LOGGER.info(msg)
    if len(msg) > MAX_MESSAGE_LENGTH:
        with io.BytesIO(str.encode(msg)) as out_file:
            out_file.name = "status.text"
            await client.send_document(
                chat_id=message.chat.id,
                document=out_file,
            )
    else:
        await message.reply_text(msg, quote=True)
コード例 #11
0
async def upload_document_f(client, message):
    imsegd = await message.reply_text(
        "processing ..."
    )
    if message.from_user.id in AUTH_CHANNEL:
        if " " in message.text:
            recvd_command, local_file_name = message.text.split(" ", 1)
            recvd_response = await upload_to_tg(
                imsegd,
                local_file_name,
                message.from_user.id,
                {}
            )
            LOGGER.info(recvd_response)
    await imsegd.delete()
コード例 #12
0
async def incoming_youtube_dl_f(client, message):
    """ /ytdl command """
    i_m_sefg = await message.reply_text("processing", quote=True)
    # LOGGER.info(message)
    # extract link from message
    dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link(
        message.reply_to_message, "YTDL"
    )
    LOGGER.info(f"extracted /ytdl links {dl_url}")
    # LOGGER.info(cf_name)
    if dl_url is not None:
        current_user_id = message.from_user.id
        # create an unique directory
        user_working_dir = os.path.join(
            Config.DOWNLOAD_LOCATION,
            str(current_user_id),
            str(message.reply_to_message.message_id),
        )
        # create download directory, if not exist
        if not os.path.isdir(user_working_dir):
            os.makedirs(user_working_dir)
        LOGGER.info("fetching youtube_dl formats")
        # list the formats, and display in button markup formats
        thumb_image, text_message, reply_markup = await extract_youtube_dl_formats(
            dl_url,
            # cf_name,
            yt_dl_user_name,
            yt_dl_pass_word,
            user_working_dir,
        )
        if thumb_image is not None:
            thumb_image = await proc_ess_image_aqon(thumb_image, user_working_dir)
            await message.reply_photo(
                photo=thumb_image,
                quote=True,
                caption=text_message,
                reply_to_message_id=message.reply_to_message.message_id,
                reply_markup=reply_markup,
            )
            os.remove(thumb_image)
            await i_m_sefg.delete()
        else:
            await i_m_sefg.edit_text(text=text_message, reply_markup=reply_markup)
    else:
        await i_m_sefg.edit_text(
            "**FCUK**! wat have you entered. \nPlease read /help \n"
            f"<b>API Error</b>: {cf_name}"
        )
コード例 #13
0
async def button(bot, update: CallbackQuery):
    LOGGER.info(update)
    if update.from_user.id != update.message.reply_to_message.from_user.id:
        return

    await update.answer()
    cb_data = update.data

    if cb_data.startswith("leech"):
        await leech_btn_k(update.message, cb_data)

    elif cb_data.startswith("ytdl"):
        await ytdl_btn_k(update.message)

    elif "|" in cb_data:
        await youtube_dl_call_back(bot, update)
コード例 #14
0
async def upload_document_f(client, message):
    imsegd = await message.reply_text(Loilacaztion.PROCESSING)
    if " " in message.text:
        recvd_command, local_file_name = message.text.split(" ", 1)
        local_file_name = os.path.realpath(
            os.path.join(DOWNLOAD_LOCATION, local_file_name))
        real_download_location = os.path.realpath(DOWNLOAD_LOCATION)
        LOGGER.info(os.path.realpath(local_file_name))
        if os.path.commonprefix(
            (local_file_name,
             real_download_location)) != real_download_location:
            imsegd = await message.reply_text("U wot m8?")
            return
        recvd_response = await upload_to_tg(imsegd, local_file_name,
                                            message.from_user.id, {})
        LOGGER.info(recvd_response)
    await imsegd.delete()
コード例 #15
0
async def yt_playlist_downg(message, i_m_sefg, client, G_DRIVE):
    url = None
    if message.reply_to_message:
        url = message.reply_to_message.text
    else:
        url = message.text.split()[1]
    usr = message.message_id
    messa_ge = i_m_sefg.reply_to_message
    fol_der = f"{usr}youtube"
    try:
        os.mkdir(fol_der)
    except:
        pass
    cmd = [
        "youtube-dl",
        "-i",
        "-f",
        "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4",
        "-o",
        f"{fol_der}/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s",
        f"{url}",
    ]
    gau_tam = await asyncio.create_subprocess_exec(
        *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )
    gau, tam = await gau_tam.communicate()
    LOGGER.info(gau.decode("utf-8"))
    LOGGER.info(tam.decode("utf-8"))
    e_response = tam.decode().strip()
    ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see  https://yt-dl.org/update  on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output."
    if e_response and ad_string_to_replace in e_response:
        error_message = e_response.replace(ad_string_to_replace, "")
        await i_m_sefg.edit_text(error_message)
        return False, None
    if G_DRIVE:
        get_g = os.listdir(fol_der)
        for ga_u in get_g:
            ta_m = os.path.join(fol_der, ga_u)
            await upload_to_gdrive(ta_m, i_m_sefg, message, usr)
    else:
        final_response = await upload_to_tg(i_m_sefg, fol_der, usr, {}, client)
    try:
        shutil.rmtree(fol_der)
    except:
        pass
コード例 #16
0
async def status_message_f(client, message):
    if await AdminCheck(client, message.chat.id, message.from_user.id):
        aria_i_p = await aria_start()
        # Show All Downloads
        downloads = aria_i_p.get_downloads()
        #
        DOWNLOAD_ICON = "📥"
        UPLOAD_ICON = "📤"
        #
        msg = ""
        for download in downloads:
            downloading_dir_name = "NA"
            try:
                downloading_dir_name = str(download.name)
            except:
                pass
            total_length_size = str(download.total_length_string())
            progress_percent_string = str(download.progress_string())
            down_speed_string = str(download.download_speed_string())
            up_speed_string = str(download.upload_speed_string())
            download_current_status = str(download.status)
            e_t_a = str(download.eta_string())
            current_gid = str(download.gid)
            #
            msg += f"<u>{downloading_dir_name}</u>"
            msg += " | "
            msg += f"{total_length_size}"
            msg += " | "
            msg += f"{progress_percent_string}"
            msg += " | "
            msg += f"{DOWNLOAD_ICON} {down_speed_string}"
            msg += " | "
            msg += f"{UPLOAD_ICON} {up_speed_string}"
            msg += " | "
            msg += f"{e_t_a}"
            msg += " | "
            msg += f"{download_current_status}"
            msg += " | "
            msg += f"<code>{Commandi.CANCEL} {current_gid}</code>"
            msg += " | "
            msg += "\n\n"
        LOGGER.info(msg)
        if msg == "":
            msg = "🤷‍♂️ No Active, Queued or Paused TORRENTs"
        await message.reply_text(msg, quote=True)
コード例 #17
0
async def rclone_button_callback(bot, update: CallbackQuery):

    """rclone button callback"""

    if update.data == "rcloneCancel":

        config.read("rclone.conf")

        section = config.sections()[0]

        await update.message.edit_text(

            f"Opration canceled! \n\nThe default section of rclone config is: **{section}**"

        )

        LOGGER.info(

            f"Opration canceled! The default section of rclone config is: {section}"

        )

    else:

        section = update.data.split("_", maxsplit=1)[1]

        with open("rclone.conf", "w", newline="\n", encoding="utf-8") as f:

            config.read("rclone_bak.conf")

            temp = configparser.ConfigParser()

            temp[section] = config[section]

            temp.write(f)

        await update.message.edit_text(

            f"Default rclone config changed to **{section}**"

        )

        LOGGER.info(f"Default rclone config changed to {section}")
コード例 #18
0
async def rclone_button_callback(bot, update: CallbackQuery):
    """rclone button callback"""
    if update.data == "rcloneCancel":
        config.read("rclone.conf")
        section = config.sections()[0]
        await update.message.edit_text(
            f"Operasi dibatalkan! \n\nSetting rclone default adalah: **{section}**"
        )
        LOGGER.info(
            f"Operasi dibatalkan! Setting default rclone adalah: {section}")
    else:
        section = update.data.split("_", maxsplit=1)[1]
        with open("rclone.conf", "w", newline="\n", encoding="utf-8") as f:
            config.read("rclone_bak.conf")
            temp = configparser.ConfigParser()
            temp[section] = config[section]
            temp.write(f)
        await update.message.edit_text(f"rclone diubah ke **{section}**")
        LOGGER.info(f"rclone diubah ke {section}")
コード例 #19
0
def add_url(aria_instance, text_url, c_file_name):
    options = None
    # if c_file_name is not None:
    #     options = {
    #         "dir": c_file_name
    #     }
    if "zippyshare.com" in text_url \
        or "osdn.net" in text_url \
        or "mediafire.com" in text_url \
        or "cloud.mail.ru" in text_url \
        or "github.com" in text_url \
        or "yadi.sk" in text_url  \
        or "letsupload.io" in text_url  \
        or "hxfile.co" in text_url  \
        or "layarkacaxxi.icu" in text_url  \
        or "naniplay.nanime.in" in text_url  \
        or "naniplay.nanime.biz" in text_url  \
        or "naniplay.com" in text_url  \
        or "femax20.com" in text_url  \
        or "sbembed.com" in text_url  \
        or "streamsb.net" in text_url  \
        or "fembed.com" in text_url  \
        or "antfiles.com" in text_url  \
        or "streamtape.com" in text_url  \
        or "1drv.ms" in text_url  \
        or "racaty.net" in text_url:
            try:
                urisitring = direct_link_generator(text_url)
                uris = [urisitring]
            except DirectDownloadLinkException as e:
                LOGGER.info(f'{text_url}: {e}')
    else:
        uris = [text_url]
    # Add URL Into Queue
    try:
        download = aria_instance.add_uris(uris, options=options)
    except Exception as e:
        return (
            False,
            "**ERROR** \n" + str(e) + " \nCan't reached link or link too slow",
        )
    else:
        return True, "" + download.gid + ""
コード例 #20
0
async def unzip_me(input_directory):
    return_name = None
    if os.path.exists(input_directory):
        base_dir_name = os.path.basename(input_directory)
        uncompressed_file_name = os.path.splitext(base_dir_name)[0]
        g_cmd = ["./extract", f"{input_directory}"]
        ga_utam = await asyncio.create_subprocess_exec(
            *g_cmd,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        # Wait for the subprocess to finish
        gau, tam = await ga_utam.communicate()
        LOGGER.info(gau.decode().strip())
        LOGGER.info(tam.decode().strip())
        if os.path.exists(uncompressed_file_name):
            try:
                os.remove(input_directory)
            except:
                pass
            return_name = uncompressed_file_name
    return return_name
コード例 #21
0
async def untar_me(input_directory):
    return_name = None
    if os.path.exists(input_directory):
        print(input_directory)
        base_dir_name = os.path.basename(input_directory)
        uncompressed_file_name = os.path.splitext(base_dir_name)[0]
        m_k_gaut = ["mkdir", f"{uncompressed_file_name}"]
        await asyncio.create_subprocess_exec(*m_k_gaut,
                                             stdout=asyncio.subprocess.PIPE,
                                             stderr=asyncio.subprocess.PIPE)
        g_cmd_t = [
            "tar",
            "-xvf",
            f"/app/{base_dir_name}",
            "-C",
            f"{uncompressed_file_name}",
        ]
        bc_kanger = await asyncio.create_subprocess_exec(
            *g_cmd_t,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        # Wait for the subprocess to finish
        mc, kanger = await bc_kanger.communicate()
        LOGGER.info(mc)
        LOGGER.info(kanger)
        # e_response = stderr.decode().strip()
        # t_response = stdout.decode().strip()
        if os.path.exists(uncompressed_file_name):
            try:
                os.remove(input_directory)
            except:
                pass
            return_name = uncompressed_file_name
            LOGGER.info(return_name)
    return return_name
コード例 #22
0
async def download_tg(client, message):
    user_id = message.from_user.id
    LOGGER.info(user_id)
    mess_age = await message.reply_text("...", quote=True)
    if not os.path.isdir(DOWNLOAD_LOCATION):
        os.makedirs(DOWNLOAD_LOCATION)
    if message.reply_to_message is not None:
        start_t = datetime.now()
        download_location = str(Path("./").resolve()) + "/"
        c_time = time.time()
        prog = Progress(user_id, client, mess_age)
        try:
            the_real_download_location = await client.download_media(
                message=message.reply_to_message,
                file_name=download_location,
                progress=prog.progress_for_pyrogram,
                progress_args=("trying to download", c_time),
            )
        except Exception as g_e:
            await mess_age.edit(str(g_e))
            LOGGER.error(g_e)
            return
        end_t = datetime.now()
        ms = (end_t - start_t).seconds
        LOGGER.info(the_real_download_location)
        await asyncio.sleep(5)
        if the_real_download_location:
            await mess_age.edit_text(
                f"Downloaded to <code>{the_real_download_location}</code> in <u>{ms}</u> seconds"
            )
        else:
            await mess_age.edit_text(
                "😔 Download Cancelled or some error happened")
            return
    return the_real_download_location, mess_age
コード例 #23
0
async def unrar_me(input_directory):
    return_name = None
    if os.path.exists(input_directory):
        base_dir_name = os.path.basename(input_directory)
        uncompressed_file_name = os.path.splitext(base_dir_name)[0]
        m_k_gau = ["mkdir", f"{uncompressed_file_name}"]
        await asyncio.create_subprocess_exec(*m_k_gau,
                                             stdout=asyncio.subprocess.PIPE,
                                             stderr=asyncio.subprocess.PIPE)
        print(base_dir_name)
        gau_tam_r = [
            "unrar", "x", f"{base_dir_name}", f"{uncompressed_file_name}"
        ]
        jai_hind = await asyncio.create_subprocess_exec(
            *gau_tam_r,
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE)
        # Wait for the subprocess to finish
        jai, hind = await jai_hind.communicate()
        LOGGER.info(jai)
        LOGGER.info(hind)
        # e_response = stderr.decode().strip()
        # t_response = stdout.decode().strip()
        if os.path.exists(uncompressed_file_name):
            try:
                os.remove(input_directory)
            except:
                pass
            return_name = uncompressed_file_name
            LOGGER.info(return_name)
    return return_name
コード例 #24
0
async def aria_start():
    aria2_daemon_start_cmd = []
    # start the daemon, aria2c command
    aria2_daemon_start_cmd.append("aria2c")
    aria2_daemon_start_cmd.append("--conf-path=/app/tobrot/aria2/aria2.conf")
    aria2_daemon_start_cmd.append("--allow-overwrite=true")
    aria2_daemon_start_cmd.append("--daemon=true")
    # aria2_daemon_start_cmd.append(f"--dir={DOWNLOAD_LOCATION}")
    # TODO: this does not work, need to investigate this.
    # but for now, https://t.me/TrollVoiceBot?start=858
    aria2_daemon_start_cmd.append("--enable-rpc")
    aria2_daemon_start_cmd.append("--disk-cache=0")
    aria2_daemon_start_cmd.append("--follow-torrent=mem")
    aria2_daemon_start_cmd.append("--max-connection-per-server=16")
    aria2_daemon_start_cmd.append("--min-split-size=10M")
    aria2_daemon_start_cmd.append("--rpc-listen-all=false")
    aria2_daemon_start_cmd.append(f"--rpc-listen-port={ARIA_TWO_STARTED_PORT}")
    aria2_daemon_start_cmd.append("--rpc-max-request-size=1024M")
    aria2_daemon_start_cmd.append("--seed-ratio=0.01")
    aria2_daemon_start_cmd.append("--seed-time=1")
    aria2_daemon_start_cmd.append("--max-overall-upload-limit=2M")
    aria2_daemon_start_cmd.append("--split=16")
    aria2_daemon_start_cmd.append(
        f"--bt-stop-timeout={MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START}")
    #
    LOGGER.info(aria2_daemon_start_cmd)
    #
    process = await asyncio.create_subprocess_exec(
        *aria2_daemon_start_cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    stdout, stderr = await process.communicate()

    aria2 = aria2p.API(
        aria2p.Client(host="http://localhost",
                      port=ARIA_TWO_STARTED_PORT,
                      secret=""))
    return aria2
コード例 #25
0
ファイル: icntaosrtsba.py プロジェクト: DeadpoolBoss/TG-Leech
async def leech_btn_k(message: Message, cb_data: str):
    # get link from the incoming message
    dl_url, cf_name, _, _ = await extract_link(message.reply_to_message,
                                               "LEECH")
    LOGGER.info(dl_url)
    LOGGER.info(cf_name)
    current_user_id = message.reply_to_message.from_user.id
    # create an unique directory
    new_download_location = os.path.join(
        DOWNLOAD_LOCATION, str(current_user_id),
        str(message.reply_to_message.message_id))
    # create download directory, if not exist
    if not os.path.isdir(new_download_location):
        os.makedirs(new_download_location)
    if dl_url is not None:
        await message.edit_text("extracting links")
        if "_" in cb_data:
            await message.edit_text("trying to download")
            # try to download the "link"
            sagtus, err_message = await fake_etairporpa_call(
                aria2, dl_url, new_download_location, message,
                int(cb_data.split("_")[2])
                # maybe IndexError / ValueError might occur,
                # we don't know, yet!!
            )
            if not sagtus:
                # if FAILED, display the error message
                await message.edit_text(err_message)
        else:
            is_zip = False
            if "a" in cb_data:
                is_zip = True
            await message.edit_text("trying to download")
            # try to download the "link"
            sagtus, err_message = await call_apropriate_function(
                aria2, dl_url, new_download_location, message, is_zip)
            if not sagtus:
                # if FAILED, display the error message
                await message.edit_text(err_message)
コード例 #26
0
async def incoming_youtube_dl_f(client, message):
    """ /ytdl command """
    current_user_id = message.from_user.id
    credit = await message.reply_text(
        f"💀 Downloading for you <a href='tg://user?id={current_user_id}'>🤕</a>",
        parse_mode="html",
    )
    await asyncio.sleep(5)
    await credit.delete()
    i_m_sefg = await message.reply_text("processing...", quote=True)
    # LOGGER.info(message)
    # extract link from message
    if message.reply_to_message:
        dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link(
            message.reply_to_message, "YTDL")
        LOGGER.info(dl_url)
        LOGGER.info(cf_name)
    elif len(message.command) == 2:
        dl_url = message.command[1]
        LOGGER.info(dl_url)
        cf_name = None
        yt_dl_user_name = None
        yt_dl_pass_word = None
        cf_name = None
    else:
        await i_m_sefg.edit("😔 No downloading source provided 🙄")
        return
    if dl_url is not None:
        await i_m_sefg.edit_text("extracting links")
        # create an unique directory
        user_working_dir = os.path.join(DOWNLOAD_LOCATION,
                                        str(current_user_id))
        # create download directory, if not exist
        if not os.path.isdir(user_working_dir):
            os.makedirs(user_working_dir)
        # list the formats, and display in button markup formats
        thumb_image, text_message, reply_markup = await extract_youtube_dl_formats(
            dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word,
            user_working_dir)
        if thumb_image is not None:
            req = requests.get(f"{thumb_image}")
            thumb_img = f"{current_user_id}.jpg"
            with open(thumb_img, "wb") as thumb:
                thumb.write(req.content)
            await message.reply_photo(
                # text_message,
                photo=thumb_img,
                quote=True,
                caption=text_message,
                reply_markup=reply_markup,
            )
            await i_m_sefg.delete()
        else:
            await i_m_sefg.edit_text(text=text_message,
                                     reply_markup=reply_markup)
    else:
        await i_m_sefg.edit_text(
            "**FCUK**! wat have you entered. \nPlease read /help \n"
            f"<b>API Error</b>: {cf_name}")
コード例 #27
0
async def incoming_message_f(client, message):
    """/leech command"""
    g_id = message.from_user.id
    credit = await message.reply_text(
        f"🧲 Leeching for you <a href='tg://user?id={g_id}'>🤕</a>",
        parse_mode="html")
    i_m_sefg = await message.reply_text("processing", quote=True)
    is_zip = False
    is_unzip = False
    is_unrar = False
    is_untar = False
    if len(message.command) > 1:
        if message.command[1].lower() == "archive":
            is_zip = True
        elif message.command[1].lower() == "unzip":
            is_unzip = True
        elif message.command[1].lower() == "unrar":
            is_unrar = True
        elif message.command[1].lower() == "untar":
            is_untar = True
    # get link from the incoming message
    dl_url, cf_name, _, _ = await extract_link(message.reply_to_message,
                                               "LEECH")
    LOGGER.info(dl_url)
    LOGGER.info(cf_name)
    if dl_url is not None:
        await i_m_sefg.edit_text("extracting links")
        # start the aria2c daemon
        aria_i_p = await aria_start()
        LOGGER.info(aria_i_p)
        current_user_id = message.from_user.id
        # create an unique directory
        new_download_location = os.path.join(DOWNLOAD_LOCATION,
                                             str(current_user_id),
                                             str(time.time()))
        # create download directory, if not exist
        if not os.path.isdir(new_download_location):
            os.makedirs(new_download_location)
        await i_m_sefg.edit_text("trying to download")
        # try to download the "link"
        sagtus, err_message = await call_apropriate_function(
            aria_i_p,
            dl_url,
            new_download_location,
            i_m_sefg,
            is_zip,
            cf_name,
            is_unzip,
            is_unrar,
            is_untar,
            message,
        )
        if not sagtus:
            # if FAILED, display the error message
            await i_m_sefg.edit_text(err_message)
    else:
        await i_m_sefg.edit_text(
            "**FCUK**! wat have you entered. \nPlease read /help \n"
            f"<b>API Error</b>: {cf_name}")
コード例 #28
0
 def get_id(self):
     mes = self.mess
     txt = mes.reply_to_message.text
     LOGGER.info(txt)
     mess = txt.split(" ", maxsplit=1)
     if len(mess) == 2:
         self.g_id = mess[0]
         LOGGER.info(self.g_id)
         self.name = mess[1]
         LOGGER.info(self.name)
     else:
         self.g_id = mess[0]
         LOGGER.info(self.g_id)
         self.name = ""
     return self.g_id, self.name
コード例 #29
0
async def incoming_youtube_dl_f(client, message):
    """ /ytdl command """
    current_user_id = message.from_user.id
    #u_men = message.from_user.mention
    #credit = await message.reply_text(
    #f"<b>⚙ Leeching For :</b> {u_men}",
    #parse_mode="html",
    #)
    i_m_sefg = await message.reply_text("<code>Prrocessing...🔃</code>",
                                        quote=True)
    # LOGGER.info(message)
    # extract link from message
    if message.reply_to_message:
        dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link(
            message.reply_to_message, "YTDL")
        LOGGER.info(dl_url)
        LOGGER.info(cf_name)
    elif len(message.command) == 2:
        dl_url = message.command[1]
        LOGGER.info(dl_url)
        cf_name = None
        yt_dl_user_name = None
        yt_dl_pass_word = None
        cf_name = None
    else:
        await i_m_sefg.edit("🐈 𝐎𝐩𝐩𝐬 𝐑𝐞𝐩𝐥𝐲 𝐰𝐢𝐭𝐡 𝐘𝐨𝐮𝐓𝐮𝐛𝐞 𝐕𝐢𝐝𝐞𝐨𝐬 𝐋𝐢𝐧𝐤.")
        return
    if dl_url is not None:
        await i_m_sefg.edit_text("extracting links")
        # create an unique directory
        user_working_dir = os.path.join(DOWNLOAD_LOCATION,
                                        str(current_user_id))
        # create download directory, if not exist
        if not os.path.isdir(user_working_dir):
            os.makedirs(user_working_dir)
        # list the formats, and display in button markup formats
        thumb_image, text_message, reply_markup = await extract_youtube_dl_formats(
            dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word,
            user_working_dir)
        if thumb_image is not None:
            req = requests.get(f"{thumb_image}")
            thumb_img = f"{current_user_id}.jpg"
            with open(thumb_img, "wb") as thumb:
                thumb.write(req.content)
            await message.reply_photo(
                # text_message,
                photo=thumb_img,
                quote=True,
                caption=text_message,
                reply_markup=reply_markup,
            )
            await i_m_sefg.delete()
        else:
            await i_m_sefg.edit_text(text=text_message,
                                     reply_markup=reply_markup)
    else:
        await i_m_sefg.edit_text("**FCUK**! wat have you entered \n"
                                 f"<b>API Error</b>: {cf_name}")
コード例 #30
0
async def aria_start():
    aria2_daemon_start_cmd = []
    # start the daemon, aria2c command
    aria2_daemon_start_cmd.append("aria2c")
    aria2_daemon_start_cmd.append("--allow-overwrite=true")
    aria2_daemon_start_cmd.append("--daemon=true")
    aria2_daemon_start_cmd.append("--enable-rpc=true")
    aria2_daemon_start_cmd.append("--netrc-path=/root/.netrc")
    aria2_daemon_start_cmd.append(f"--rpc-listen-port={ARIA_TWO_STARTED_PORT}")
    aria2_daemon_start_cmd.append("--rpc-listen-all=false")
    aria2_daemon_start_cmd.append("--check-certificate=false")
    # aria2_daemon_start_cmd.append("--enable-dht")
    # aria2_daemon_start_cmd.append("--dht-listen-port=6881")
    aria2_daemon_start_cmd.append("--follow-metalink=mem")
    aria2_daemon_start_cmd.append("--max-connection-per-server=14")
    aria2_daemon_start_cmd.append("--rpc-max-request-size=1024M")
    aria2_daemon_start_cmd.append("--bt-max-peers=0")
    aria2_daemon_start_cmd.append("--seed-time=0.01")
    aria2_daemon_start_cmd.append("--min-split-size=10M")
    aria2_daemon_start_cmd.append("--follow-torrent=mem")
    aria2_daemon_start_cmd.append("--split=10")
    aria2_daemon_start_cmd.append("--allow-overwrite=true")
    aria2_daemon_start_cmd.append("--max-overall-upload-limit=1K")
    aria2_daemon_start_cmd.append("--peer-id-prefix=-qB4350-")
    aria2_daemon_start_cmd.append("--user-agent=qBittorrent/4.3.5")
    aria2_daemon_start_cmd.append("--peer-agent=qBittorrent/4.3.5")
    aria2_daemon_start_cmd.append("--disk-cache=64M")
    aria2_daemon_start_cmd.append("--file-allocation=prealloc")
    aria2_daemon_start_cmd.append("--continue=true")
    aria2_daemon_start_cmd.append("--bt-request-peer-speed-limit=2048K")
    aria2_daemon_start_cmd.append("--max-file-not-found=5")
    aria2_daemon_start_cmd.append("--max-tries=20")
    aria2_daemon_start_cmd.append("--auto-file-renaming=true")
    aria2_daemon_start_cmd.append("--bt-enable-lpd=true")
    aria2_daemon_start_cmd.append("--seed-ratio=1.0")
    aria2_daemon_start_cmd.append("--content-disposition-default-utf8=true")
    aria2_daemon_start_cmd.append("--http-accept-gzip=true")
    aria2_daemon_start_cmd.append("--reuse-uri=true")
    aria2_daemon_start_cmd.append(f"--bt-tracker={sonstringtrckr}")
    aria2_daemon_start_cmd.append("--seed-time=0")
    aria2_daemon_start_cmd.append(
        f"--bt-stop-timeout={MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START}"
    )
    #
    LOGGER.info(aria2_daemon_start_cmd)
    #
    process = await asyncio.create_subprocess_exec(
        *aria2_daemon_start_cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    stdout, stderr = await process.communicate()
    LOGGER.info(stdout)
    LOGGER.info(stderr)
    aria2 = aria2p.API(
        aria2p.Client(host="http://localhost", port=ARIA_TWO_STARTED_PORT, secret="")
    )
    return aria2