Skip to content

Commit

Permalink
sync with latest
Browse files Browse the repository at this point in the history
  • Loading branch information
5hojib committed Dec 28, 2024
1 parent b76520e commit 0369615
Show file tree
Hide file tree
Showing 21 changed files with 330 additions and 117 deletions.
4 changes: 2 additions & 2 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
FROM 5hojib/aeon:beta
FROM 5hojib/aeon:latest

WORKDIR /usr/src/app
RUN chmod 777 /usr/src/app

COPY requirements.txt .
RUN pip3 install --break-system-packages --ignore-installed --no-cache-dir -r requirements.txt
RUN uv pip install --break-system-packages --system --no-cache-dir -r requirements.txt

COPY . .
CMD ["bash", "start.sh"]
30 changes: 29 additions & 1 deletion bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
update_qb_options,
update_variables,
)
from .helper.ext_utils.bot_utils import create_help_buttons, sync_to_async
from .helper.ext_utils.bot_utils import create_help_buttons, sync_to_async, new_task
from .helper.ext_utils.files_utils import clean_all, exit_clean_up
from .helper.ext_utils.telegraph_helper import telegraph
from .helper.listeners.aria2_listener import start_aria2_listener
Expand All @@ -23,9 +23,31 @@
initiate_search_tools,
restart_notification,
)
from .helper.telegram_helper.filters import CustomFilters
from pyrogram.filters import regex
from pyrogram.handlers import CallbackQueryHandler

Config.load()

@new_task
async def restart_sessions_confirm(_, query):
data = query.data.split()
message = query.message
if data[1] == "confirm":
reply_to = message.reply_to_message
restart_message = await send_message(reply_to, "Restarting Session(s)...")
await delete_message(message)
await TgClient.reload()
add_handlers()
TgClient.bot.add_handler(
CallbackQueryHandler(
restart_sessions_confirm,
filters=regex("^sessionrestart") & CustomFilters.sudo,
)
)
await edit_message(restart_message, "Session(s) Restarted Successfully!")
else:
await delete_message(message)

async def main():
await load_settings()
Expand All @@ -47,6 +69,12 @@ async def main():
)
create_help_buttons()
add_handlers()
TgClient.bot.add_handler(
CallbackQueryHandler(
restart_sessions_confirm,
filters=regex("^sessionrestart") & CustomFilters.sudo,
)
)
LOGGER.info("Bot Started!")
signal(SIGINT, exit_clean_up)

Expand Down
12 changes: 6 additions & 6 deletions bot/core/config_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,12 @@ def load(cls):
for attr in dir(settings):
if hasattr(cls, attr):
value = getattr(settings, attr)
if isinstance(value, str):
value = value.strip()
if not value:
continue
if attr == "DEFAULT_UPLOAD" and value != "rc":
value = "gd"
if isinstance(value, str):
value = value.strip()
if attr == "DEFAULT_UPLOAD" and value != "gd":
value = "rc"
elif attr == "DOWNLOAD_DIR" and not value.endswith("/"):
value = f"{value}/"
setattr(cls, attr, value)
Expand All @@ -104,8 +104,8 @@ def load(cls):
def load_dict(cls, config_dict):
for key, value in config_dict.items():
if hasattr(cls, key):
if key == "DEFAULT_UPLOAD" and value != "rc":
value = "gd"
if key == "DEFAULT_UPLOAD" and value != "gd":
value = "rc"
elif key == "DOWNLOAD_DIR":
if not value.endswith("/"):
value = f"{value}/"
Expand Down
13 changes: 13 additions & 0 deletions bot/core/handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -288,3 +288,16 @@ def add_handlers():
& CustomFilters.authorized,
),
)
TgClient.bot.add_handler(
CallbackQueryHandler(
confirm_restart, filters=regex("^botrestart") & CustomFilters.sudo
)
)
TgClient.bot.add_handler(
MessageHandler(
restart_sessions,
filters=command(BotCommands.RestartSessionsCommand, case_sensitive=True)
& CustomFilters.sudo,
)
)

6 changes: 3 additions & 3 deletions bot/core/startup.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,9 +209,6 @@ async def update_variables():
else:
index_urls.append("")

if not await aiopath.exists("accounts"):
Config.USE_SERVICE_ACCOUNTS = False


async def load_configurations():
if not await aiopath.exists(".netrc"):
Expand Down Expand Up @@ -240,3 +237,6 @@ async def load_configurations():
).wait()
await (await create_subprocess_exec("chmod", "-R", "777", "accounts")).wait()
await remove("accounts.zip")

if not await aiopath.exists("accounts"):
Config.USE_SERVICE_ACCOUNTS = False
8 changes: 7 additions & 1 deletion bot/helper/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ async def before_start(self):
)
)

if is_telegram_link(self.thumb):
if self.thumb != "none" and is_telegram_link(self.thumb):
msg = (await get_tg_link_message(self.thumb))[0]
self.thumb = (
await create_thumb(msg) if msg.photo or msg.document else ""
Expand Down Expand Up @@ -1199,6 +1199,9 @@ async def proceed_ffmpeg(self, dl_path, gid):
res = await run_ffmpeg_cmd(self, cmd, file_path)
if res and delete_files:
await remove(file_path)
if "ffmpeg." in res:
newres = res.replace("ffmpeg.", "")
await move(res, newres)
else:
for dirpath, _, files in await sync_to_async(
walk,
Expand Down Expand Up @@ -1233,6 +1236,9 @@ async def proceed_ffmpeg(self, dl_path, gid):
res = await run_ffmpeg_cmd(self, cmd, f_path)
if res and delete_files:
await remove(f_path)
if "ffmpeg." in res:
newres = res.replace("ffmpeg.", "")
await move(res, newres)
if checked:
cpu_eater_lock.release()
return dl_path
57 changes: 34 additions & 23 deletions bot/helper/ext_utils/bot_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,8 +91,14 @@ async def get_telegraph_list(telegraph_content):


def arg_parser(items, arg_base):

if not items:
return

arg_start = -1
i = 0
total = len(items)

bool_arg_set = {
"-b",
"-e",
Expand All @@ -110,16 +116,28 @@ def arg_parser(items, arg_base):
"-doc",
"-med",
}
t = len(items)
i = 0
arg_start = -1

while i + 1 <= t:
def process_argument_with_values(start_index):
values = []
for j in range(start_index + 1, total):
if items[j] in arg_base:
break
values.append(items[j])
return values

def process_nested_list(start_index):
values = []
end_index = start_index + 1
while end_index < total and items[end_index] != "]":
values.append(items[end_index])
end_index += 1
return values, end_index - start_index

while i < total:
part = items[i]
if part in arg_base:
if arg_start == -1:
arg_start = i
if (i + 1 == t and part in bool_arg_set) or part in [
if (i + 1 == total and part in bool_arg_set) or part in [
"-s",
"-j",
"-f",
Expand All @@ -131,27 +149,20 @@ def arg_parser(items, arg_base):
"-med",
]:
arg_base[part] = True
elif part == "-ff" and i + 1 < total and items[i + 1].startswith("["):
nested_values, skip_count = process_nested_list(i + 1)
arg_base[part] = nested_values
i += skip_count
else:
sub_list = []
for j in range(i + 1, t):
item = items[j]
if item in arg_base:
if part in bool_arg_set and not sub_list:
arg_base[part] = True
break
sub_list.append(item)
i += 1
sub_list = process_argument_with_values(i)
if sub_list:
arg_base[part] = " ".join(sub_list)
i += len(sub_list)
i += 1
if "link" in arg_base and items[0] not in arg_base:
link = []
if arg_start == -1:
link.extend(iter(items))
else:
link.extend(items[r] for r in range(arg_start))
if link:
arg_base["link"] = " ".join(link)
if "link" in arg_base:
link_items = items[:arg_start] if arg_start != -1 else items
if link_items:
arg_base["link"] = " ".join(link_items)


def get_size_bytes(size):
Expand Down
2 changes: 1 addition & 1 deletion bot/helper/ext_utils/help_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@

thumb = """<b>Thumbnail for current task</b>: -t
/cmd link -t tg-message-link(doc or photo)"""
/cmd link -t tg-message-link (doc or photo) or none (file without thumb)"""

split_size = """<b>Split size for current task</b>: -sp
Expand Down
6 changes: 3 additions & 3 deletions bot/helper/ext_utils/status_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,13 @@ class MirrorStatus:
"AR": MirrorStatus.STATUS_ARCHIVE,
"EX": MirrorStatus.STATUS_EXTRACT,
"SD": MirrorStatus.STATUS_SEED,
"CL": MirrorStatus.STATUS_CLONE,
"CM": MirrorStatus.STATUS_CONVERT,
"SP": MirrorStatus.STATUS_SPLIT,
"CK": MirrorStatus.STATUS_CHECK,
"SV": MirrorStatus.STATUS_SAMVID,
"FF": MirrorStatus.STATUS_FFMPEG,
"CL": MirrorStatus.STATUS_CLONE,
"PA": MirrorStatus.STATUS_PAUSED,
"CK": MirrorStatus.STATUS_CHECK,
}


Expand Down Expand Up @@ -245,7 +245,7 @@ async def get_readable_message(sid, is_user, page_no=1, status="All", page_step=
for i in [1, 2, 4, 6, 8, 10, 15]:
buttons.data_button(i, f"status {sid} ps {i}", position="footer")
if status != "All" or tasks_no > 20:
for label, status_value in list(STATUSES.items())[:9]:
for label, status_value in list(STATUSES.items()):
if status_value != status:
buttons.data_button(label, f"status {sid} st {status_value}")
buttons.data_button("♻️", f"status {sid} ref", position="header")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -174,4 +174,4 @@ async def cancel_task(self):
LOGGER.info(
f"Cancelling download on user request: name: {self._listener.name} id: {self._id}",
)
await self._on_download_error("Cancelled by user!")
await self._on_download_error("Stopped by user!")
10 changes: 5 additions & 5 deletions bot/helper/mirror_leech_utils/download_utils/yt_dlp_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ def _extract_meta_data(self):
if not entry:
continue
if "filesize_approx" in entry:
self._listener.size += entry["filesize_approx"]
self._listener.size += entry.get("filesize_approx", 0)
elif "filesize" in entry:
self._listener.size += entry["filesize"]
self._listener.size += entry.get("filesize", 0)
if not self._listener.name:
outtmpl_ = "%(series,playlist_title,channel)s%(season_number& |)s%(season_number&S|)s%(season_number|)02d.%(ext)s"
self._listener.name, ext = ospath.splitext(
Expand Down Expand Up @@ -197,8 +197,8 @@ def _download(self, path):
if self._listener.is_cancelled:
return
async_to_sync(self._listener.on_download_complete)
except ValueError:
self._on_download_error("Download Stopped by User!")
except Exception:
pass

async def add_download(self, path, qual, playlist, options):
if playlist:
Expand Down Expand Up @@ -352,7 +352,7 @@ async def add_download(self, path, qual, playlist, options):
async def cancel_task(self):
self._listener.is_cancelled = True
LOGGER.info(f"Cancelling Download: {self._listener.name}")
await self._listener.on_download_error("Download Cancelled by User!")
await self._listener.on_download_error("Stopped by User!")

def _set_options(self, options):
options = options.split("|")
Expand Down
2 changes: 1 addition & 1 deletion bot/helper/mirror_leech_utils/gdrive_utils/helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ async def cancel_task(self):
self.listener.is_cancelled = True
if self.is_downloading:
LOGGER.info(f"Cancelling Download: {self.listener.name}")
await self.listener.on_download_error("Download stopped by user!")
await self.listener.on_download_error("Stopped by user!")
elif self.is_cloning:
LOGGER.info(f"Cancelling Clone: {self.listener.name}")
await self.listener.on_upload_error(
Expand Down
2 changes: 1 addition & 1 deletion bot/helper/mirror_leech_utils/rclone_utils/transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,7 @@ async def cancel_task(self):
self._proc.kill()
if self._is_download:
LOGGER.info(f"Cancelling Download: {self._listener.name}")
await self._listener.on_download_error("Download stopped by user!")
await self._listener.on_download_error("Stopped by user!")
elif self._is_upload:
LOGGER.info(f"Cancelling Upload: {self._listener.name}")
await self._listener.on_upload_error("your upload has been stopped!")
Expand Down
10 changes: 7 additions & 3 deletions bot/helper/mirror_leech_utils/telegram_uploader.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ async def _user_settings(self):
if "lprefix" not in self._listener.user_dict
else ""
)
if not await aiopath.exists(self._thumb):
if self._thumb != "none" and not await aiopath.exists(self._thumb):
self._thumb = None

async def _msg_to_reply(self):
Expand Down Expand Up @@ -398,7 +398,7 @@ async def upload(self, o_files, ft_delete):
retry=retry_if_exception_type(Exception),
)
async def _upload_file(self, cap_mono, file, o_path, force_document=False):
if self._thumb is not None and not await aiopath.exists(self._thumb):
if self._thumb is not None and not await aiopath.exists(self._thumb) and self._thumb != "none":
self._thumb = None
thumb = self._thumb
self._is_corrupted = False
Expand All @@ -424,6 +424,8 @@ async def _upload_file(self, cap_mono, file, o_path, force_document=False):

if self._listener.is_cancelled:
return None
if thumb == "none":
thumb = None
self._sent_msg = await self._sent_msg.reply_document(
document=self._up_path,
quote=True,
Expand All @@ -444,14 +446,16 @@ async def _upload_file(self, cap_mono, file, o_path, force_document=False):
)
if thumb is None:
thumb = await get_video_thumbnail(self._up_path, duration)
if thumb is not None:
if thumb is not None and thumb != "none":
with Image.open(thumb) as img:
width, height = img.size
else:
width = 480
height = 320
if self._listener.is_cancelled:
return None
if thumb == "none":
thumb = None
self._sent_msg = await self._sent_msg.reply_video(
video=self._up_path,
quote=True,
Expand Down
1 change: 1 addition & 0 deletions bot/helper/telegram_helper/bot_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def __init__(self):
self.RmSudoCommand = f"rmsudo{Config.CMD_SUFFIX}"
self.PingCommand = f"ping{Config.CMD_SUFFIX}"
self.RestartCommand = f"restart{Config.CMD_SUFFIX}"
self.RestartSessionsCommand = f"restartses{Config.CMD_SUFFIX}"
self.StatsCommand = f"stats{Config.CMD_SUFFIX}"
self.HelpCommand = f"help{Config.CMD_SUFFIX}"
self.LogCommand = f"log{Config.CMD_SUFFIX}"
Expand Down
Loading

0 comments on commit 0369615

Please sign in to comment.