Some fixes for jdownloader

add aioexec and remove eval(it was useless in code not used)

Signed-off-by: anasty17 <e.anastayyar@gmail.com>
This commit is contained in:
anasty17 2024-01-01 01:40:30 +02:00
parent b67db09e23
commit ee60a514ed
7 changed files with 52 additions and 32 deletions

View File

@ -384,8 +384,8 @@ cancelall - Cancel all tasks
del - Delete file/folder from Drive
log - Get the Bot Log
shell - Run commands in Shell
eval - Execute function
exec - Execute function
aexec - Execute async function
exec - Execute sync function
restart - Restart the Bot
stats - Bot Usage Stats
ping - Ping the Bot

View File

@ -42,6 +42,7 @@ from .modules import (
authorize,
cancel_task,
clone,
exec,
gd_count,
gd_delete,
gd_search,
@ -52,7 +53,6 @@ from .modules import (
ytdlp,
rss,
shell,
eval,
users_settings,
bot_settings,
help,
@ -174,9 +174,9 @@ NOTE: Try each command without any argument to see more detalis.
/{BotCommands.RestartCommand}: Restart and update the bot (Only Owner & Sudo).
/{BotCommands.LogCommand}: Get a log file of the bot. Handy for getting crash reports (Only Owner & Sudo).
/{BotCommands.ShellCommand}: Run shell commands (Only Owner).
/{BotCommands.EvalCommand}: Run Python Code Line | Lines (Only Owner).
/{BotCommands.ExecCommand}: Run Commands In Exec (Only Owner).
/{BotCommands.ClearLocalsCommand}: Clear {BotCommands.EvalCommand} or {BotCommands.ExecCommand} locals (Only Owner).
/{BotCommands.AExecCommand}: Exec async functions (Only Owner).
/{BotCommands.ExecCommand}: Exec sync functions (Only Owner).
/{BotCommands.ClearLocalsCommand}: Clear {BotCommands.AExecCommand} or {BotCommands.ExecCommand} locals (Only Owner).
/{BotCommands.RssCommand}: RSS Menu.
"""

View File

@ -119,12 +119,17 @@ class JDownloader(Myjdapi):
@new_task
async def keepJdAlive(self):
while True:
await aiosleep(180)
await aiosleep(100)
if self.device is None:
break
try:
await sync_to_async(self.reconnect)
except:
pass
async with jd_lock:
try:
if not await sync_to_async(self.reconnect):
LOGGER.error("Failed to reconnect!")
continue
await sync_to_async(self.device.enable_direct_connection)
except:
pass
jdownloader = JDownloader()

View File

@ -103,8 +103,9 @@ async def add_jd_download(listener, path):
jdownloader.device.linkgrabber.add_links,
[
{
"links": listener.link,
"autoExtract": False,
"destinationFolder": path,
"links": listener.link,
"overwritePackagizerRules": True,
"packageName": listener.name or None,
}
@ -125,14 +126,17 @@ async def add_jd_download(listener, path):
],
)
packages = []
online = 0
for pack in queued_downloads:
if pack["saveTo"] == path:
save_to = pack["saveTo"]
if save_to.startswith(path):
if len(packages) == 0:
name = pack["name"]
gid = pack["uuid"]
size = pack.get("bytesTotal", 0)
jd_downloads[gid] = "collect"
if pack.get("onlineCount", 1) == 0:
online += pack.get("onlineCount", 1)
if online == 0:
await listener.onDownloadError(name)
return
packages.append(pack["uuid"])
@ -141,7 +145,13 @@ async def add_jd_download(listener, path):
await retry_function(
jdownloader.device.action,
"/linkgrabberv2/movetoNewPackage",
[[], packages, name, path],
[[], packages, name, f"{path}/{name}"],
)
elif online > 1 and save_to == path:
await retry_function(
jdownloader.device.action,
"/linkgrabberv2/setDownloadDirectory",
[f"{path}/{name}", packages],
)
if len(packages) == 1:
@ -193,7 +203,7 @@ async def add_jd_download(listener, path):
)
exists = False
for pack in download_packages:
if pack["saveTo"] == path:
if pack["saveTo"].startswith(path):
async with jd_lock:
del jd_downloads[gid]
gid = pack["uuid"]

View File

@ -31,7 +31,7 @@ class _BotCommands:
self.HelpCommand = f"help{CMD_SUFFIX}"
self.LogCommand = f"log{CMD_SUFFIX}"
self.ShellCommand = f"shell{CMD_SUFFIX}"
self.EvalCommand = f"eval{CMD_SUFFIX}"
self.AExecCommand = f"aexec{CMD_SUFFIX}"
self.ExecCommand = f"exec{CMD_SUFFIX}"
self.ClearLocalsCommand = f"clearlocals{CMD_SUFFIX}"
self.BotSetCommand = [f"bsetting{CMD_SUFFIX}", f"bs{CMD_SUFFIX}"]

View File

@ -5,6 +5,7 @@ from traceback import format_exc
from textwrap import indent
from io import StringIO, BytesIO
from contextlib import redirect_stdout
from aiofiles import open as aiopen
from bot import LOGGER, bot
from bot.helper.telegram_helper.filters import CustomFilters
@ -45,13 +46,13 @@ async def send(msg, message):
@new_task
async def evaluate(_, message):
await send(await sync_to_async(do, eval, message), message)
async def aioexecute(_, message):
await send(await do("aexec", message), message)
@new_task
async def execute(_, message):
await send(await sync_to_async(do, exec, message), message)
await send(await do("exec", message), message)
def cleanup_code(code):
@ -60,30 +61,34 @@ def cleanup_code(code):
return code.strip("` \n")
def do(func, message):
async def do(func, message):
log_input(message)
content = message.text.split(maxsplit=1)[-1]
body = cleanup_code(content)
env = namespace_of(message)
chdir(getcwd())
with open(ospath.join(getcwd(), "bot/modules/temp.txt"), "w") as temp:
temp.write(body)
async with aiopen(ospath.join(getcwd(), "bot/modules/temp.txt"), "w") as temp:
await temp.write(body)
stdout = StringIO()
to_compile = f'def func():\n{indent(body, " ")}'
try:
exec(to_compile, env)
if func == "exec":
exec(f"def func():\n{indent(body, ' ')}", env)
else:
exec(f"async def func():\n{indent(body, ' ')}", env)
except Exception as e:
return f"{e.__class__.__name__}: {e}"
func = env["func"]
rfunc = env["func"]
try:
with redirect_stdout(stdout):
func_return = func()
if func == "exec":
func_return = await sync_to_async(rfunc)
else:
func_return = await rfunc()
except Exception as e:
value = stdout.getvalue()
return f"{value}{format_exc()}"
@ -95,7 +100,7 @@ def do(func, message):
result = f"{value}"
else:
try:
result = f"{repr(eval(body, env))}"
result = f"{repr(await sync_to_async(eval, body, env))}"
except:
pass
else:
@ -104,7 +109,7 @@ def do(func, message):
return result
async def clear(client, message):
async def clear(_, message):
log_input(message)
global namespaces
if message.chat.id in namespaces:
@ -114,7 +119,7 @@ async def clear(client, message):
bot.add_handler(
MessageHandler(
evaluate, filters=command(BotCommands.EvalCommand) & CustomFilters.owner
aioexecute, filters=command(BotCommands.AExecCommand) & CustomFilters.owner
)
)
bot.add_handler(

View File

@ -295,7 +295,7 @@ class Mirror(TaskListener):
try:
await add_jd_download(self, path)
except (Exception, MYJDException) as e:
await sendMessage(f"{e}".strip())
await sendMessage(self.message, f"{e}".strip())
self.removeFromSameDir()
return
elif is_rclone_path(self.link):