From e4dd79cda5b8ef3e475da814e581d0fc1752ddaf Mon Sep 17 00:00:00 2001 From: yasirarism <55983182+yasirarism@users.noreply.github.com> Date: Tue, 6 Jun 2023 15:27:09 +0000 Subject: [PATCH] Tes genss by link --- misskaty/core/decorator/__init__.py | 3 +- misskaty/helper/ssgen_helper.py | 126 ---------------------------- misskaty/helper/tools.py | 11 ++- misskaty/plugins/genss.py | 107 +++++++++++++++++------ 4 files changed, 92 insertions(+), 155 deletions(-) delete mode 100644 misskaty/helper/ssgen_helper.py diff --git a/misskaty/core/decorator/__init__.py b/misskaty/core/decorator/__init__.py index 364bd068..1e50e486 100644 --- a/misskaty/core/decorator/__init__.py +++ b/misskaty/core/decorator/__init__.py @@ -1,3 +1,4 @@ from .errors import * from .misc import * -from .permissions import * \ No newline at end of file +from .permissions import * +from .ratelimiter import * \ No newline at end of file diff --git a/misskaty/helper/ssgen_helper.py b/misskaty/helper/ssgen_helper.py deleted file mode 100644 index aac4f523..00000000 --- a/misskaty/helper/ssgen_helper.py +++ /dev/null @@ -1,126 +0,0 @@ -import datetime -import os -import random -import shlex -import time -import traceback -import uuid -import asyncio -from pathlib import Path - -from pyrogram import enums -from pyrogram.types import InlineKeyboardButton, InputMediaPhoto - -from misskaty.vars import FF_MPEG_NAME - - -async def run_subprocess(cmd): - process = await asyncio.create_subprocess_shell(cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) - return await process.communicate() - - -def get_random_start_at(seconds, dur=0): - return random.randint(0, seconds - dur) - - -async def get_duration(input_file_link): - ffmpeg_dur_cmd = f"ffprobe -v error -show_entries format=duration -of csv=p=0:s=x -select_streams v:0 {shlex.quote(input_file_link)}" - # print(ffmpeg_dur_cmd) - out, err = await run_subprocess(ffmpeg_dur_cmd) - if out := out.decode().strip(): - return duration if (duration := round(float(out))) else "No duration!" - else: - return err.decode() - - -def is_url(text): - return text.startswith("http") - - -async def get_dimentions(input_file_link): - ffprobe_cmd = f"ffprobe -v error -show_entries stream=width,height -of csv=p=0:s=x -select_streams v:0 {shlex.quote(input_file_link)}" - output = await run_subprocess(ffprobe_cmd) - try: - width, height = [int(i.strip()) for i in output[0].decode().split("x")] - except Exception as e: - print(e) - width, height = 1280, 534 - return width, height - - -async def screenshot_flink(c, m): - m.from_user.id - # if c.CURRENT_PROCESSES.get(chat_id, 0) == 1: - # return await m.answer('You have reached the maximum parallel processes! Try again after one of them finishes.', show_alert=True) - # if not c.CURRENT_PROCESSES.get(chat_id): - # c.CURRENT_PROCESSES[chat_id] = 0 - # c.CURRENT_PROCESSES[chat_id] += 1 - - _, num_screenshots = m.data.split("+") - num_screenshots = int(num_screenshots) - media_msg = m.message.reply_to_message - # print(media_msg) - if media_msg.empty: - await m.message.edit_msg("Why did you delete the file 😠, Now i cannot help you πŸ˜’.") - # c.CURRENT_PROCESSES[chat_id] -= 1 - return - - uid = str(uuid.uuid4()) - output_folder = Path("GenSS/").joinpath(uid) - if not output_folder.exists(): - os.makedirs(output_folder) - - try: - start_time = time.time() - - await m.message.edit_msg("Give me some time bruh!! 😴") - - await m.message.edit_msg("πŸ˜€ Taking Snaps!") - file_link = m.message.reply_to_message.command[1] - duration = await get_duration(file_link) - if isinstance(duration, str): - return await m.message.edit_msg("Oops, What's that? Couldn't Open the file😟.") - - reduced_sec = duration - int(duration * 2 / 100) - print(f"Total seconds: {duration}, Reduced seconds: {reduced_sec}") - screenshots = [] - ffmpeg_errors = "" - - screenshot_secs = [get_random_start_at(reduced_sec) for _ in range(1, 1 + num_screenshots)] - width, height = await get_dimentions(file_link) - - for i, sec in enumerate(screenshot_secs): - thumbnail_template = output_folder.joinpath(f"{i+1}.png") - ffmpeg_cmd = f"{FF_MPEG_NAME} -hide_banner -ss {sec} -i {shlex.quote(file_link)} -vframes 1 '{thumbnail_template}'" - output = await run_subprocess(ffmpeg_cmd) - await m.message.edit_msg(f"πŸ˜€ `{i+1}` of `{num_screenshots}` generated!") - if thumbnail_template.exists(): - screenshots.append(InputMediaPhoto(str(thumbnail_template), caption=f"ScreenShot at {datetime.timedelta(seconds=sec)}")) - continue - ffmpeg_errors += output[1].decode() + "\n\n" - - if not screenshots: - return await m.message.edit_msg("😟 Sorry! Screenshot generation failed possibly due to some infrastructure failure πŸ˜₯.") - - await m.message.edit_msg("πŸ€“ Its done , Now starting to upload!") - await media_msg.reply_chat_action(enums.ChatAction.UPLOAD_PHOTO) - await media_msg.reply_media_group(screenshots, True) - - await m.message.edit_msg(f"Completed in {datetime.timedelta(seconds=int(time.time()-start_time))}\n\nJoin @YasirPediaChannel\n\n©️ https://yasirpedia.eu.org") - - except: - traceback.print_exc() - await m.message.edit_msg("😟 Sorry! Screenshot generation failed, ERR: {aa} πŸ˜₯.") - - -def gen_ik_buttons(): - btns = [] - i_keyboard = [] - for i in range(2, 11): - i_keyboard.append(InlineKeyboardButton(f"{i}", f"scht+{i}")) - if (i > 2) and (i % 2) == 1: - btns.append(i_keyboard) - i_keyboard = [] - if i == 10: - btns.append(i_keyboard) - return btns diff --git a/misskaty/helper/tools.py b/misskaty/helper/tools.py index ee5bcad5..fd501bab 100644 --- a/misskaty/helper/tools.py +++ b/misskaty/helper/tools.py @@ -5,6 +5,7 @@ import time import logging from http.cookies import SimpleCookie from urllib.parse import urlparse +from re import match as re_match import psutil @@ -14,7 +15,7 @@ from misskaty.helper.human_read import get_readable_time from misskaty.plugins import ALL_MODULES LOGGER = logging.getLogger(__name__) - +URL_REGEX = "(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])" GENRES_EMOJI = { "Action": "πŸ‘Š", "Adventure": random.choice(["πŸͺ‚", "πŸ§—β€β™€", "πŸŒ‹"]), @@ -41,6 +42,11 @@ GENRES_EMOJI = { } +def is_url(url): + url = re_match(URL_REGEX, url) + return bool(url) + + async def bot_sys_stats(): bot_uptime = int(time.time() - botStartTime) cpu = psutil.cpu_percent(interval=0.5) @@ -138,6 +144,3 @@ async def search_jw(movie_name: str, locale: str): m_t_ = m_t_[:-2].strip() break return m_t_ - - -SUPPORTED_URL_REGEX = {r"(http|ftp|https):\/\/([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])": "ddl"} diff --git a/misskaty/plugins/genss.py b/misskaty/plugins/genss.py index a5403769..e656c615 100644 --- a/misskaty/plugins/genss.py +++ b/misskaty/plugins/genss.py @@ -1,15 +1,15 @@ """ * @author yasir * @date 2022-12-01 09:12:27 - * @lastModified 2022-12-01 09:32:31 * @projectName MissKatyPyro * Copyright @YasirPedia All rights reserved """ -import datetime import os import time -from asyncio import gather, sleep, create_task +from asyncio import gather, sleep +from datetime import datetime from logging import getLogger +from pySmartDL import SmartDL from pyrogram import enums, filters, Client from pyrogram.errors import FloodWait @@ -17,9 +17,9 @@ from pyrogram.file_id import FileId from pyrogram.types import InlineKeyboardMarkup, Message, CallbackQuery from misskaty import app -from misskaty.core.decorator.ratelimiter import ratelimiter +from misskaty.core.decorator import ratelimiter, new_task from misskaty.core.misskaty_patch.listen.listen import ListenerTimeout -from misskaty.helper import gen_ik_buttons, get_duration, is_url, progress_for_pyrogram, screenshot_flink, take_ss +from misskaty.helper import is_url, progress_for_pyrogram, take_ss from misskaty.helper.localization import use_chat_lang from misskaty.vars import COMMAND_HANDLER @@ -34,26 +34,91 @@ __HELP__ = """" @app.on_message(filters.command(["genss"], COMMAND_HANDLER)) @ratelimiter +@new_task @use_chat_lang() async def genss(self: Client, ctx: Message, strings): if not ctx.from_user: return replied = ctx.reply_to_message if len(ctx.command) == 2 and is_url(ctx.command[1]): - snt = await ctx.reply_msg(strings("wait_msg"), quote=True) - - duration = await get_duration(ctx.command[1]) - if isinstance(duration, str): - return await snt.edit_msg(strings("fail_open")) - btns = gen_ik_buttons() - msg = await snt.edit_msg(strings("choose_no_ss").format(td=datetime.timedelta(seconds=duration), dur=duration), reply_markup=InlineKeyboardMarkup(btns)) - try: - await msg.wait_for_click( - from_user_id=ctx.from_user.id, - timeout=30 + pesan = await ctx.reply_msg(strings("wait_msg"), quote=True) + start_t = datetime.now() + the_url_parts = " ".join(message.command[1:]) + url = the_url_parts.strip() + file_name = os.path.basename(url) + download_file_path = os.path.join("downloads/", file_name) + downloader = SmartDL(url, download_file_path, progress_bar=False, timeout=10) + downloader.start(blocking=False) + c_time = time.time() + while not downloader.isFinished(): + total_length = downloader.filesize or None + downloaded = downloader.get_dl_size(human=True) + display_message = "" + now = time.time() + diff = now - c_time + percentage = downloader.get_progress() * 100 + speed = downloader.get_speed(human=True) + progress_str = "[{0}{1}]\nProgress: {2}%".format( + "".join(["β–ˆ" for _ in range(math.floor(percentage / 5))]), + "".join(["β–‘" for _ in range(20 - math.floor(percentage / 5))]), + round(percentage, 2), ) - except ListenerTimeout: - await msg.edit_msg(strings("exp_task", context="general")) + + estimated_total_time = downloader.get_eta(human=True) + try: + current_message = "Trying to download...\n" + current_message += f"URL: {url}\n" + current_message += f"File Name: {custom_file_name}\n" + current_message += f"Speed: {speed}\n" + current_message += f"{progress_str}\n" + current_message += f"{downloaded} of {humanbytes(total_length)}\n" + current_message += f"ETA: {estimated_total_time}" + if round(diff % 10.00) == 0 and current_message != display_message: + await pesan.edit(disable_web_page_preview=True, text=current_message) + display_message = current_message + await sleep(10) + except Exception as e: + LOGGER.info(str(e)) + if os.path.exists(download_file_path): + end_t = datetime.now() + ms = (end_t - start_t).seconds + await pesan.edit(f"Downloaded to {download_file_path} in {ms} seconds") + try: + images = await take_ss(the_real_download_location) + await process.edit_msg(strings("up_progress")) + await self.send_chat_action(chat_id=ctx.chat.id, action=enums.ChatAction.UPLOAD_PHOTO) + try: + await gather( + *[ + ctx.reply_document(images, reply_to_message_id=ctx.id), + ctx.reply_photo(images, reply_to_message_id=ctx.id), + ] + ) + except FloodWait as e: + await sleep(e.value) + await gather( + *[ + ctx.reply_document(images, reply_to_message_id=ctx.id), + ctx.reply_photo(images, reply_to_message_id=ctx.id), + ] + ) + await ctx.reply_msg( + strings("up_msg").format(namma=ctx.from_user.mention, id=ctx.from_user.id, bot_uname=self.me.username), + reply_to_message_id=ctx.id, + ) + await pesan.delete() + try: + os.remove(images) + os.remove(the_real_download_location) + except: + pass + except Exception as exc: + await ctx.reply_msg(strings("err_ssgen").format(exc=exc)) + try: + os.remove(images) + os.remove(the_real_download_location) + except: + pass elif replied and replied.media: vid = [replied.video, replied.document] media = next((v for v in vid if v is not None), None) @@ -112,9 +177,3 @@ async def genss(self: Client, ctx: Message, strings): pass else: await ctx.reply_msg(strings("no_reply"), del_in=6) - - -@app.on_callback_query(filters.regex(r"^scht")) -@ratelimiter -async def genss_cb(self: Client, cb: CallbackQuery): - create_task(screenshot_flink(self, cb))