Skip to content

Commit

Permalink
Update
Browse files Browse the repository at this point in the history
- No mood to write description.
  • Loading branch information
5hojib authored Jun 6, 2024
1 parent d6ab6b5 commit b8b36e5
Show file tree
Hide file tree
Showing 19 changed files with 164 additions and 196 deletions.
42 changes: 29 additions & 13 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
faulthandler_enable()
install()
setdefaulttimeout(600)
getLogger("telegraph").setLevel(ERROR)
getLogger("pymongo").setLevel(ERROR)
getLogger("httpx").setLevel(ERROR)
botStartTime = time()

class CustomFormatter(Formatter):
Expand Down Expand Up @@ -419,12 +420,31 @@ def format(self, record):
alive = Popen(['python3', 'alive.py'])
sleep(0.5)

aria2 = ariaAPI(ariaClient(host="http://localhost", port=6800, secret=""))


def get_client():
return qbClient(host="localhost", port=8090, VERIFY_WEBUI_CERTIFICATE=False, REQUESTS_ARGS={'timeout': (30, 60)})

aria2 = ariaAPI(
ariaClient(
host="http://localhost",
port=6800,
secret=""
)
)


xnox_client = qbClient(
host="localhost",
port=8090,
VERIFY_WEBUI_CERTIFICATE=False,
REQUESTS_ARGS={
"timeout": (
30,
60
)
},
HTTPADAPTER_ARGS={
"pool_maxsize": 500,
"max_retries": 10,
"pool_block": True,
},
)

def aria2c_init():
try:
Expand All @@ -451,19 +471,15 @@ def aria2c_init():
for op in aria2c_global if op in aria2_options}
aria2.set_global_options(a2c_glo)

qb_client = get_client()
if not qbit_options:
qbit_options = dict(qb_client.app_preferences())
qbit_options = dict(xnox_client.app_preferences())
del qbit_options['listen_port']
for k in list(qbit_options.keys()):
if k.startswith('rss'):
del qbit_options[k]
else:
qb_opt = {**qbit_options}
for k, v in list(qb_opt.items()):
if v in ["", "*"]:
del qb_opt[k]
qb_client.app_set_preferences(qb_opt)
xnox_client.app_set_preferences(qb_opt)

bot = tgClient('bot', TELEGRAM_API, TELEGRAM_HASH, bot_token = BOT_TOKEN, workers = 1000, parse_mode = enums.ParseMode.HTML).start()
bot_loop = bot.loop
Expand Down
93 changes: 24 additions & 69 deletions bot/helper/aeon_utils/metadata.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,18 @@
import os
import json

from asyncio import create_subprocess_exec
from asyncio.subprocess import PIPE

from bot import LOGGER

async def change_key(file, dirpath, key):
LOGGER.info(f"Trying to change metadata for file: {file}")
async def change_metadata(file, dirpath, key):
LOGGER.info(f"Starting metadata modification for file: {file}")
temp_file = f"{file}.temp.mkv"

full_file_path = os.path.join(dirpath, file)
temp_file_path = os.path.join(dirpath, temp_file)

cmd = [
'ffprobe', '-hide_banner', '-loglevel', 'error', '-print_format', 'json', '-show_streams', full_file_path
]

process = await create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = await process.communicate()

Expand All @@ -32,8 +28,8 @@ async def change_key(file, dirpath, key):

cmd = [
'xtra', '-y', '-i', full_file_path, '-c', 'copy',
'-metadata', f'title={key}',
'-metadata:s:v:0', f'title={key}',
'-metadata', f'title={key}',
'-metadata', 'copyright=',
'-metadata', 'description=',
'-metadata', 'license=',
Expand Down Expand Up @@ -62,80 +58,45 @@ async def change_key(file, dirpath, key):

audio_index = 0
subtitle_index = 0
first_video = False

for stream in streams:
stream_index = stream['index']
stream_type = stream['codec_type']

cmd.extend(['-map', f'0:{stream_index}'])

if stream_type == 'audio':
cmd.extend([f'-metadata:s:a:{audio_index}', f'title={key}'])
if stream_type == 'video':
if not first_video:
cmd.extend(['-map', f'0:{stream_index}'])
first_video = True
cmd.extend([f'-metadata:s:v:{stream_index}', f'title={key}'])
elif stream_type == 'audio':
cmd.extend(['-map', f'0:{stream_index}', f'-metadata:s:a:{audio_index}', f'title={key}'])
audio_index += 1
elif stream_type == 'subtitle':
cmd.extend([f'-metadata:s:s:{subtitle_index}', f'title={key}'])
subtitle_index += 1
codec_name = stream.get('codec_name', 'unknown')
if codec_name in ['webvtt', 'unknown']:
LOGGER.warning(f"Skipping unsupported subtitle metadata modification: {codec_name} for stream {stream_index}")
else:
cmd.extend(['-map', f'0:{stream_index}', f'-metadata:s:s:{subtitle_index}', f'title={key}'])
subtitle_index += 1
else:
cmd.extend(['-map', f'0:{stream_index}'])

cmd.append(temp_file_path)

process = await create_subprocess_exec(*cmd, stderr=PIPE)
await process.wait()
process = await create_subprocess_exec(*cmd, stderr=PIPE, stdout=PIPE)
stdout, stderr = await process.communicate()

if process.returncode != 0:
err = (await process.stderr.read()).decode().strip()
err = stderr.decode().strip()
LOGGER.error(err)
LOGGER.error(f"Error changing metadata for file: {file}")
return file

os.replace(temp_file_path, full_file_path)
LOGGER.info(f"Metadata changed successfully for file: {file}")
return file


async def delete_extra_streams(file, dirpath):
temp_file = f"{file}.temp.mkv"

full_file_path = os.path.join(dirpath, file)
temp_file_path = os.path.join(dirpath, temp_file)

cmd = ['ffprobe', '-hide_banner', '-loglevel', 'error', '-print_format', 'json', '-show_streams', full_file_path]
process = await create_subprocess_exec(*cmd, stdout=PIPE, stderr=PIPE)
stdout, stderr = await process.communicate()

if process.returncode != 0:
LOGGER.error(f"Error getting stream info: {stderr.decode().strip()}")
LOGGER.error(f"Error modifying metadata for file: {file}")
return file

try:
streams = json.loads(stdout)['streams']
except KeyError:
LOGGER.error(f"No streams found in the ffprobe output: {stdout.decode().strip()}")
return file

cmd = ['xtra', '-y', '-i', full_file_path]

first_video = False

for stream in streams:
stream_index = stream['index']
stream_type = stream['codec_type']

if stream_type == 'video':
if not first_video:
cmd.extend(['-map', f'0:{stream_index}'])
first_video = True
else:
cmd.extend(['-map', f'0:{stream_index}'])

cmd.extend(['-c', 'copy', temp_file_path])

process = await create_subprocess_exec(*cmd, stderr=PIPE)
await process.wait()

os.replace(temp_file_path, full_file_path)
LOGGER.info(f"Metadata modified successfully for file: {file}")
return file


async def add_attachment(file, dirpath, attachment_path):
LOGGER.info(f"Adding photo attachment to file: {file}")

Expand Down Expand Up @@ -170,9 +131,3 @@ async def add_attachment(file, dirpath, attachment_path):
os.replace(temp_file_path, full_file_path)
LOGGER.info(f"Photo attachment added successfully to file: {file}")
return file


async def change_metadata(file, dirpath, key):
file = await delete_extra_streams(file, dirpath)
file = await change_key(file, dirpath, key)
return file
17 changes: 0 additions & 17 deletions bot/helper/aeon_utils/react.py

This file was deleted.

24 changes: 24 additions & 0 deletions bot/helper/aeon_utils/send_react.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from random import choice
from bot import bot, LOGGER

async def send_react(message):
try:
chat_id = int(message.chat.id)
chat_info = await bot.get_chat(chat_id)
available_reactions = chat_info.available_reactions

full_emoji_set = {'👌', '🔥', '🥰', '❤️', '❤️‍🔥', '💯', '⚡', '💋', '😘', '🤩', '😍'}

if available_reactions:
if getattr(available_reactions, "all_are_enabled", False):
emojis = full_emoji_set
else:
emojis = {reaction.emoji for reaction in available_reactions.reactions}

await message.react(choice(list(emojis)), big=True)
except AttributeError as e:
LOGGER.error(f"AttributeError: {e}")
except TypeError as e:
LOGGER.error(f"TypeError: {e}")
except Exception as e:
LOGGER.error(f"An unexpected error occurred: {e}")
14 changes: 1 addition & 13 deletions bot/helper/ext_utils/bot_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from pyrogram.errors import PeerIdInvalid

from bot.helper.ext_utils.db_handler import DbManager
from bot import OWNER_ID, bot_name, DATABASE_URL, LOGGER, get_client, aria2, download_dict, download_dict_lock, botStartTime, user_data, config_dict, bot_loop, extra_buttons, user
from bot import OWNER_ID, bot_name, DATABASE_URL, LOGGER, aria2, download_dict, download_dict_lock, botStartTime, user_data, config_dict, bot_loop, extra_buttons, user
from bot.helper.telegram_helper.bot_commands import BotCommands
from bot.helper.telegram_helper.button_build import ButtonMaker
from bot.helper.ext_utils.telegraph_helper import telegraph
Expand Down Expand Up @@ -236,16 +236,6 @@ def get_readable_message():
msg += f"\n<blockquote>/stop_{download.gid()[:8]}</blockquote>\n\n"
if len(msg) == 0:
return None, None
dl_speed = 0
up_speed = 0
for download in download_dict.values():
tstatus = download.status()
if tstatus == MirrorStatus.STATUS_DOWNLOADING:
dl_speed += text_to_bytes(download.speed())
elif tstatus == MirrorStatus.STATUS_UPLOADING:
up_speed += text_to_bytes(download.speed())
elif tstatus == MirrorStatus.STATUS_SEEDING:
up_speed += text_to_bytes(download.upload_speed())
if tasks > STATUS_LIMIT:
buttons = ButtonMaker()
buttons.ibutton("Prev", "status pre")
Expand All @@ -255,8 +245,6 @@ def get_readable_message():
msg += f"<b>• Tasks</b>: {tasks}{bmax_task}"
msg += f"\n<b>• Bot uptime</b>: {currentTime}"
msg += f"\n<b>• Free disk space</b>: {get_readable_file_size(disk_usage('/usr/src/app/downloads/').free)}"
msg += f"\n<b>• Uploading speed</b>: {get_readable_file_size(up_speed)}/s"
msg += f"\n<b>• Downloading speed</b>: {get_readable_file_size(dl_speed)}/s"
return msg, button


Expand Down
6 changes: 3 additions & 3 deletions bot/helper/ext_utils/files_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from natsort import natsorted
from magic import Magic

from bot import LOGGER, MAX_SPLIT_SIZE, config_dict, user_data, aria2, get_client, GLOBAL_EXTENSION_FILTER
from bot import LOGGER, MAX_SPLIT_SIZE, config_dict, user_data, aria2, xnox_client, GLOBAL_EXTENSION_FILTER
from bot.modules.mediainfo import parseinfo
from bot.helper.ext_utils.bot_utils import cmd_exec, sync_to_async, get_readable_file_size, get_readable_time, isMkv
from bot.helper.ext_utils.telegraph_helper import telegraph
Expand Down Expand Up @@ -415,7 +415,7 @@ async def clean_download(path):


async def start_cleanup():
get_client().torrents_delete(torrent_hashes="all")
xnox_client.torrents_delete(torrent_hashes="all")
try:
await aiormtree('/usr/src/app/downloads/')
except:
Expand All @@ -425,7 +425,7 @@ async def start_cleanup():

def clean_all():
aria2.remove_all(True)
get_client().torrents_delete(torrent_hashes="all")
xnox_client.torrents_delete(torrent_hashes="all")
try:
rmtree('/usr/src/app/downloads/')
except:
Expand Down
1 change: 0 additions & 1 deletion bot/helper/ext_utils/telegraph_helper.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

from bot import LOGGER, bot_loop

getLogger("telegraph").setLevel(ERROR)

class TelegraphHelper:
def __init__(self):
Expand Down
Loading

0 comments on commit b8b36e5

Please sign in to comment.