Skip to content

Commit

Permalink
Some fixes for jdownloader
Browse files Browse the repository at this point in the history
add aioexec and remove eval(it was useless in code not used)

Signed-off-by: anasty17 <[email protected]>
  • Loading branch information
anasty17 committed Dec 31, 2023
1 parent b67db09 commit ee60a51
Show file tree
Hide file tree
Showing 7 changed files with 52 additions and 32 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
authorize,
cancel_task,
clone,
exec,
gd_count,
gd_delete,
gd_search,
Expand All @@ -52,7 +53,6 @@
ytdlp,
rss,
shell,
eval,
users_settings,
bot_settings,
help,
Expand Down Expand Up @@ -174,9 +174,9 @@ async def log(_, message):
/{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.
"""

Expand Down
15 changes: 10 additions & 5 deletions bot/helper/ext_utils/jdownloader_booter.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,12 +119,17 @@ def connectToDevice(self):
@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()
20 changes: 15 additions & 5 deletions bot/helper/mirror_utils/download_utils/jd_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
Expand All @@ -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"])
Expand All @@ -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:
Expand Down Expand Up @@ -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"]
Expand Down
2 changes: 1 addition & 1 deletion bot/helper/telegram_helper/bot_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(self):
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}"]
Expand Down
33 changes: 19 additions & 14 deletions bot/modules/eval.py → bot/modules/exec.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
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
Expand Down Expand Up @@ -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):
Expand All @@ -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()}"
Expand All @@ -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:
Expand All @@ -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:
Expand All @@ -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(
Expand Down
2 changes: 1 addition & 1 deletion bot/modules/mirror_leech.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ async def newEvent(self):
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):
Expand Down

0 comments on commit ee60a51

Please sign in to comment.