コード例 #1
0
async def ff_mpeg_trim_cmd(event):
    if event.fwd_from:
        return
    if not os.path.exists(FF_MPEG_DOWN_LOAD_MEDIA_PATH):
        await event.edit(
            f"a media file needs to be downloaded, and saved to the following path: `{FF_MPEG_DOWN_LOAD_MEDIA_PATH}`"
        )
        return
    current_message_text = event.raw_text
    cmt = current_message_text.split(" ")
    logger.info(cmt)
    start = datetime.now()
    if len(cmt) == 3:
        # output should be video
        cmd, start_time, end_time = cmt
        o = await cult_small_video(FF_MPEG_DOWN_LOAD_MEDIA_PATH,
                                   Config.TMP_DOWNLOAD_DIRECTORY, start_time,
                                   end_time)
        logger.info(o)
        try:
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                o,
                caption=" ".join(cmt[1:]),
                force_document=False,
                supports_streaming=True,
                allow_cache=False,
                # reply_to=event.message.id,
            )
            os.remove(o)
        except Exception as e:
            logger.info(str(e))
    elif len(cmt) == 2:
        # output should be image
        cmd, start_time = cmt
        o = await take_screen_shot(FF_MPEG_DOWN_LOAD_MEDIA_PATH,
                                   Config.TMP_DOWNLOAD_DIRECTORY, start_time)
        logger.info(o)
        try:
            c_time = time.time()
            await borg.send_file(
                event.chat_id,
                o,
                caption=" ".join(cmt[1:]),
                force_document=True,
                # supports_streaming=True,
                allow_cache=False,
                # reply_to=event.message.id,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, event, c_time, "trying to upload")))
            os.remove(o)
        except Exception as e:
            logger.info(str(e))
    else:
        await event.edit("RTFM")
        return
    end = datetime.now()
    ms = (end - start).seconds
    await event.edit(f"Completed Process in {ms} seconds")
コード例 #2
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.reply("Processing ...")
    if Config.MIRROR_ACE_API_KEY is None or Config.MIRROR_ACE_API_TOKEN is None:
        await mone.edit("This module requires API key from https://ouo.io/My1jdU. Aborting!")
        return False
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    required_file_name = None
    start = datetime.now()
    if event.reply_to_msg_id and not input_str:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
                    progress(d, t, mone, c_time, "trying to download")
                )
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
            return False
        else:
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = downloaded_file_name
            await mone.edit("Downloaded to `{}` in {} seconds.".format(downloaded_file_name, ms))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = input_str
            await mone.edit("Found `{}` in {} seconds.".format(input_str, ms))
        else:
            await mone.edit("File Not found in local server. Give me a file path :((")
            return False
    # logger.info(required_file_name)
    if required_file_name:
        # required_file_name will have the full path
        file_name = os.path.basename(required_file_name)
        file_size = os.stat(required_file_name).st_size
        # /* STEP 1: get upload_key */
        step_one_url = "https://mirrorace.com/api/v1/file/upload"
        step_one_auth_params = {
            "api_key": Config.MIRROR_ACE_API_KEY,
            "api_token": Config.MIRROR_ACE_API_TOKEN
        }
        async with aiohttp.ClientSession() as session:
            resp = await session.post(step_one_url, data=step_one_auth_params)
            # logger.info(resp.status)
            if resp.status == 200:
                step_one_response_json = await resp.json()
                logger.info(step_one_response_json)
                if step_one_response_json["status"] == "success":
                    await mone.edit("Received Upload URL from MirrorAce. ...")
                    start = datetime.now()
                    # /* STEP 2: Upload file */
                    # step one: response vars
                    step_two_upload_url = step_one_response_json["result"]["server_file"]
                    cTracker = step_one_response_json["result"]["cTracker"]
                    upload_key = step_one_response_json["result"]["upload_key"]
                    default_mirrors = step_one_response_json["result"]["default_mirrors"]
                    max_chunk_size = step_one_response_json["result"]["max_chunk_size"]
                    max_file_size = step_one_response_json["result"]["max_file_size"]
                    max_mirrors = step_one_response_json["result"]["max_mirrors"]

                    # check file size limit
                    if int(file_size) >= int(max_file_size):
                        await mone.edit(f"File exceeds maximum file size allowed: {max_file_size}")
                        return False

                    # step two: setup
                    mirrors = default_mirrors
                    chunk_size = int(max_chunk_size)
                    step_two_params = {
                        "api_key": Config.MIRROR_ACE_API_KEY,
                        "api_token": Config.MIRROR_ACE_API_TOKEN,
                        "cTracker": cTracker,
                        "upload_key": upload_key,
                        "mirrors[]": mirrors,
                        # //these required vars will be added by buildMultiPartRequest function
                        # //'files' => $file,
                        # //'mirrors[1]' => 1,
                        # //'mirrors[2]' => 2,
                    }

                    # //range vars //for multi chunk upload
                    response = False

                    with open(required_file_name, "rb") as f_handle:
                        # start chunk upload
                        for chunk in iter((lambda: f_handle.read(chunk_size)), ""):
                            # for chunk in f_handle.read(chunk_size):
                            # print(chunk)
                            # while (i < chunks) and not while_error:
                            # chunk = f_handle.read(chunk_size)
                            if not chunk:
                                break
                            headers = {
                                "Content-Range": str(len(chunk)),
                                "Content-Length": str(len(step_two_params) + len(chunk)),
                                # "Content-Type": "multipart/form-data"
                            }

                            # https://github.com/aio-libs/aiohttp/issues/3571#issuecomment-456528924
                            response = requests.post(
                                step_two_upload_url,
                                files=[("files", (file_name, chunk))],
                                data=step_two_params,
                                # headers=headers
                            )
                            logger.info(response.content)

                    logger.info(response)
                    final_response = response.json()
                    if final_response["status"] == "success":
                        end = datetime.now()
                        ms = (end - start).seconds
                        final_url = final_response["result"]["url"]
                        await mone.edit(f"Added to {final_url} in {ms} seconds")
                    else:
                        await mone.edit(f"MirrorAce returned {final_response['status']} => {final_response['result']}")
                else:
                    await mone.edit(f"MirrorAce returned {step_one_response_json['status']} => {step_one_response_json['result']}, after STEP TWO")
            else:
                await mone.edit(f"MirrorAce returned {resp['status']} => {resp['result']}, after STEP ONE")
    else:
        await mone.edit("File Not found in local server. Give me a file path :((")
コード例 #3
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    reply_message = await event.get_reply_message()
    if reply_message is None:
        await event.reply(
            "reply to a media to use the `nfc` operation.\nInspired by @FileConverterBot"
        )
        return
    await event.reply("trying to download media file, to my local")
    try:
        start = datetime.now()
        c_time = time.time()
        downloaded_file_name = await borg.download_media(
            reply_message,
            Config.TMP_DOWNLOAD_DIRECTORY,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(progress(d, t, event, c_time, "trying to download")))
    except Exception as e:  # pylint:disable=C0103,W0703
        await event.reply(str(e))
    else:
        end = datetime.now()
        ms = (end - start).seconds
        await event.reply("Downloaded to `{}` in {} seconds.".format(
            downloaded_file_name, ms))
        new_required_file_name = ""
        new_required_file_caption = ""
        command_to_run = []
        force_document = False
        voice_note = False
        supports_streaming = False
        if input_str == "voice":
            new_required_file_caption = "AUDIO" + str(round(
                time.time())) + ".opus"
            new_required_file_name = Config.TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption
            command_to_run = [
                "ffmpeg", "-i", downloaded_file_name, "-map", "0:a",
                "-codec:a", "libopus", "-b:a", "100k", "-vbr", "on",
                new_required_file_name
            ]
            voice_note = True
            supports_streaming = True
        elif input_str == "mp3":
            new_required_file_caption = "AUDIO" + str(round(
                time.time())) + ".mp3"
            new_required_file_name = Config.TMP_DOWNLOAD_DIRECTORY + "/" + new_required_file_caption
            command_to_run = [
                "ffmpeg", "-i", downloaded_file_name, "-vn",
                new_required_file_name
            ]
            voice_note = False
            supports_streaming = True
        else:
            await event.reply("not supported")
            os.remove(downloaded_file_name)
            return
        logger.info(command_to_run)
        # TODO: re-write create_subprocess_exec 😉
        process = await asyncio.create_subprocess_exec(
            *command_to_run,
            # stdout must a pipe to be accessible as process.stdout
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
        )
        # Wait for the subprocess to finish
        stdout, stderr = await process.communicate()
        e_response = stderr.decode().strip()
        t_response = stdout.decode().strip()
        os.remove(downloaded_file_name)
        if os.path.exists(new_required_file_name):
            end_two = datetime.now()
            await borg.send_file(
                entity=event.chat_id,
                file=new_required_file_name,
                caption=new_required_file_caption,
                allow_cache=False,
                silent=True,
                force_document=force_document,
                voice_note=voice_note,
                supports_streaming=supports_streaming,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, event, c_time, "trying to upload")))
            ms_two = (end_two - end).seconds
            os.remove(new_required_file_name)
            await event.reply(f"converted in {ms_two} seconds")
コード例 #4
0
async def _(event):
    if event.fwd_from:
        return
    thumb = None
    if os.path.exists(thumb_image_path):
        thumb = thumb_image_path
    ievent = await edit_or_reply(
        event,
        "`Rename & Upload in process Wait Sometime`",
    )
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        start = datetime.now()
        file_name = input_str
        reply_message = await event.get_reply_message()
        c_time = time.time()
        to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
        downloaded_file_name = os.path.join(to_download_directory, file_name)
        downloaded_file_name = await event.client.download_media(
            reply_message,
            downloaded_file_name,
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, ievent, c_time, "trying to download", file_name)
            ),
        )
        end = datetime.now()
        ms_one = (end - start).seconds
        try:
            thumb = await reply_message.download_media(thumb=-1)
        except Exception:
            thumb = thumb
        if os.path.exists(downloaded_file_name):
            c_time = time.time()
            caat = await event.client.send_file(
                event.chat_id,
                downloaded_file_name,
                force_document=False,
                supports_streaming=True,
                allow_cache=False,
                reply_to=event.message.id,
                thumb=thumb,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(
                    progress(d, t, event, c_time, "Trying To Upload",
                             downloaded_file_name)),
            )
            end_two = datetime.now()
            os.remove(downloaded_file_name)
            ms_two = (end_two - end).seconds
            await ievent.edit(
                f"`Downloaded file in {ms_one} Seconds.`\n`Uploaded in {ms_two} Seconds.`"
            )
            await asyncio.sleep(3)
            await ievent.delete()
        else:
            await ievent.edit("File Not Found {}".format(input_str))
    else:
        await ievent.edit(
            "**Syntax : **`.rnupload file.name` as reply to a Telegram media")
コード例 #5
0
async def _(event):
    if event.fwd_from:
        return
    ievent = await event.edit("Rename & Upload as Streamable in Process")
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    if event.reply_to_msg_id:
        start = datetime.now()
        file_name = input_str
        reply_message = await event.get_reply_message()
        c_time = time.time()
        to_download_directory = Config.TMP_DOWNLOAD_DIRECTORY
        downloaded_file_name = os.path.join(to_download_directory, file_name)
        downloaded_file_name = await borg.download_media(
            reply_message, downloaded_file_name)
        end_one = datetime.now()
        ms_one = (end_one - start).seconds
        if os.path.exists(downloaded_file_name):
            thumb = None
            if not downloaded_file_name.endswith(
                (".mkv", ".mp4", ".mp3", ".flac")):
                await ievent.edit(
                    "Sorry. But I don't think {} is a streamable file. Please try again.\n**Supported Formats**: MKV, MP4, MP3, FLAC"
                    .format(downloaded_file_name))
                return False
            if os.path.exists(thumb_image_path):
                thumb = thumb_image_path
            else:
                thumb = get_video_thumb(downloaded_file_name, thumb_image_path)
            start = datetime.now()
            metadata = extractMetadata(createParser(downloaded_file_name))
            duration = 0
            width = 0
            height = 0
            if metadata.has("duration"):
                duration = metadata.get("duration").seconds
            if os.path.exists(thumb_image_path):
                metadata = extractMetadata(createParser(thumb_image_path))
                if metadata.has("width"):
                    width = metadata.get("width")
                if metadata.has("height"):
                    height = metadata.get("height")
            # Telegram only works with MP4 files
            # this is good, since with MKV files sent as streamable Telegram responds,
            # Bad Request: VIDEO_CONTENT_TYPE_INVALID
            c_time = time.time()
            try:
                await borg.send_file(
                    event.chat_id,
                    downloaded_file_name,
                    thumb=thumb,
                    caption=downloaded_file_name,
                    force_document=False,
                    allow_cache=False,
                    reply_to=event.message.id,
                    attributes=[
                        DocumentAttributeVideo(
                            duration=duration,
                            w=width,
                            h=height,
                            round_message=False,
                            supports_streaming=True,
                        )
                    ],
                    progress_callback=lambda d, t: asyncio.get_event_loop().
                    create_task(
                        progress(d, t, ievent, c_time, "trying to upload")),
                )
            except Exception as e:
                await event.edit(str(e))
            else:
                end = datetime.now()
                os.remove(downloaded_file_name)
                ms_two = (end - end_one).seconds
                await ievent.edit(
                    "Downloaded in {} seconds. Uploaded in {} seconds By [Jarvis userbot](https://github.com/Jarvis-Works/JarvisUserbot)"
                    .format(ms_one, ms_two))
        else:
            await ievent.edit("File Not Found {}".format(input_str))
    else:
        await ievent.edit(
            "Syntax // .rnstreamupload file.name as reply to a Telegram media")
コード例 #6
0
ファイル: gdrivenew.py プロジェクト: kumarvns/Jarvis
async def _(event):
    if event.fwd_from:
        return
    mone = await event.reply("Processing The File ...")
    if CLIENT_ID is None or CLIENT_SECRET is None:
        await mone.edit(
            "This module requires credentials from https://da.gd/so63O. Aborting!"
        )
        return
    if Config.PLUGIN_CHANNEL is None:
        await event.edit(
            "Please set the required environment variable `PLUGIN_CHANNEL` for this plugin to work"
        )
        return
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    required_file_name = None
    start = datetime.now()
    if event.reply_to_msg_id and not input_str:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop(
                ).create_task(
                    progress(d, t, mone, c_time, "trying to download")),
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
            return False
        else:
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = downloaded_file_name
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = input_str
            await mone.edit("Found `{}` in {} seconds.".format(input_str, ms))
        else:
            await mone.edit(
                "File Not found in local server. Give me a file path :((")
            return False
    # logger.info(required_file_name)
    if required_file_name:
        #
        if Config.AUTH_TOKEN_DATA is not None:
            with open(G_DRIVE_TOKEN_FILE, "w") as t_file:
                t_file.write(Config.AUTH_TOKEN_DATA)
        # Check if token file exists, if not create it by requesting authorization code
        storage = None
        if not os.path.isfile(G_DRIVE_TOKEN_FILE):
            storage = await create_token_file(G_DRIVE_TOKEN_FILE, event)
        http = authorize(G_DRIVE_TOKEN_FILE, storage)
        # Authorize, get file parameters, upload file and print out result URL for download
        # http = authorize(G_DRIVE_TOKEN_FILE, None)
        file_name, mime_type = file_ops(required_file_name)
        # required_file_name will have the full path
        # Sometimes API fails to retrieve starting URI, we wrap it.
        try:
            g_drive_link = await upload_file(
                http,
                required_file_name,
                file_name,
                mime_type,
                mone,
                G_DRIVE_F_PARENT_ID,
            )
            await mone.edit(f"Here is your Google Drive link: {g_drive_link}")
        except Exception as e:
            await mone.edit(f"Exception occurred while uploading to gDrive {e}"
                            )
    else:
        await mone.edit(
            "File Not found in local server. Give me a file path :((")
コード例 #7
0
async def _(event):
    if event.fwd_from:
        return
    mone = await event.reply("Processing ...")
    if Config.VERY_STREAM_LOGIN is None or Config.VERY_STREAM_KEY is None:
        await mone.edit(
            "This module requires API key from https://verystream.com. Aborting!"
        )
        return False
    input_str = event.pattern_match.group(1)
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    required_file_name = None
    start = datetime.now()
    if event.reply_to_msg_id and not input_str:
        reply_message = await event.get_reply_message()
        try:
            c_time = time.time()
            downloaded_file_name = await borg.download_media(
                reply_message,
                Config.TMP_DOWNLOAD_DIRECTORY,
                progress_callback=lambda d, t: asyncio.get_event_loop().
                create_task(progress(d, t, mone, c_time, "trying to download"))
            )
        except Exception as e:  # pylint:disable=C0103,W0703
            await mone.edit(str(e))
            return False
        else:
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = downloaded_file_name
            await mone.edit("Downloaded to `{}` in {} seconds.".format(
                downloaded_file_name, ms))
    elif input_str:
        input_str = input_str.strip()
        if os.path.exists(input_str):
            end = datetime.now()
            ms = (end - start).seconds
            required_file_name = input_str
            await mone.edit("Found `{}` in {} seconds.".format(input_str, ms))
        else:
            await mone.edit(
                "File Not found in local server. Give me a file path :((")
            return False
    # logger.info(required_file_name)
    if required_file_name:
        # required_file_name will have the full path
        file_name = os.path.basename(required_file_name)
        if "." in file_name:
            file_name = file_name.rsplit(".", maxsplit=1)[0]
        file_name = file_name + str(time.time())
        file_size = os.stat(required_file_name).st_size
        # https://stackoverflow.com/a/22058673/4723940
        sha_one_file_hash = get_sha_one_hash(required_file_name, 65536)
        # /* STEP 1: get upload_key */
        login = Config.VERY_STREAM_LOGIN
        key = Config.VERY_STREAM_KEY
        sha1 = sha_one_file_hash
        mime = magic.Magic(mime=True)
        step_zero_url = f"https://api.verystream.com/file/createfolder?login={login}&key={key}&name={file_name}"
        async with aiohttp.ClientSession() as session:
            resp_zero = await session.get(step_zero_url)
            step_zero_response_text = json.loads(await resp_zero.text())
            # logger.info(step_zero_response_text)
            if step_zero_response_text["status"] == 200:
                folder_id_e = step_zero_response_text["result"]["folderid"]
                await mone.edit(f"Created Folder with ID: {folder_id_e}")
                step_one_url = f"https://api.verystream.com/file/ul?login={login}&key={key}&sha1={sha1}&folder={folder_id_e}"
                resp = await session.get(step_one_url)
                # logger.info(resp.status)
                step_one_response_text = json.loads(await resp.text())
                # logger.info(step_one_response_text)
                if step_one_response_text["status"] == 200:
                    url = step_one_response_text["result"]["url"]
                    await mone.edit(f"Start Uploading to {url}")
                    start = datetime.now()
                    files = {
                        "file1": (file_name, open(required_file_name, "rb"))
                    }
                    resp = requests.post(url, files=files)
                    step_two_response_text = resp.json()
                    # logger.info(step_two_response_text)
                    if step_two_response_text["status"] == 200:
                        output_str = json.dumps(
                            step_two_response_text["result"],
                            sort_keys=True,
                            indent=4)
                        stream_url = step_two_response_text["result"]["url"]
                        end = datetime.now()
                        ms = (end - start).seconds
                        await mone.edit(
                            f"Obtained {stream_url} in {ms} seconds.\n{output_str}"
                        )
                        # cleanup
                        await event.delete()
                        try:
                            os.remove(required_file_name)
                        except:
                            pass
                    else:
                        await mone.edit(
                            f"VeryStream returned {step_two_response_text['status']} => {step_two_response_text['msg']}, after STEP ONE"
                        )
                else:
                    await mone.edit(
                        f"VeryStream returned {step_one_response_text['status']} => {step_one_response_text['msg']}, after STEP ONE"
                    )
            else:
                await mone.edit(
                    f"VeryStream returned {step_zero_response_text['status']} => {step_zero_response_text['msg']}, after STEP INIT"
                )
    else:
        await mone.edit(
            "File Not found in local server. Give me a file path :((")