Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
5hojib committed Aug 29, 2024
1 parent 7ac7b20 commit 88a466e
Show file tree
Hide file tree
Showing 19 changed files with 96 additions and 91 deletions.
6 changes: 3 additions & 3 deletions bot/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
from subprocess import run as srun
from faulthandler import enable as faulthandler_enable

from aria2p import API as ariaAPI
from aria2p import API
from aria2p import Client as ariaClient
from dotenv import load_dotenv, dotenv_values
from uvloop import install
Expand All @@ -37,7 +37,7 @@
setdefaulttimeout(600)
getLogger("pymongo").setLevel(ERROR)
getLogger("httpx").setLevel(ERROR)
botStartTime = time()
bot_start_time = time()


class CustomFormatter(Formatter):
Expand Down Expand Up @@ -472,7 +472,7 @@ def format(self, record):
alive = Popen(["python3", "alive.py"])
sleep(0.5)

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


xnox_client = qbClient(
Expand Down
34 changes: 17 additions & 17 deletions bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
scheduler,
user_data,
config_dict,
botStartTime,
bot_start_time,
)

from .modules import (
Expand Down Expand Up @@ -107,9 +107,9 @@
async def stats(_, message):
total, used, free, disk = disk_usage("/")
memory = virtual_memory()
currentTime = get_readable_time(time() - botStartTime)
osUptime = get_readable_time(time() - boot_time())
cpuUsage = cpu_percent(interval=0.5)
current_time = get_readable_time(time() - bot_start_time)
os_uptime = get_readable_time(time() - boot_time())
cpu_usage = cpu_percent(interval=0.5)
limit_mapping = {
"Torrent": config_dict.get("TORRENT_LIMIT", "∞"),
"Gdrive": config_dict.get("GDRIVE_LIMIT", "∞"),
Expand All @@ -121,9 +121,9 @@ async def stats(_, message):
"User task": config_dict.get("USER_MAX_TASKS", "∞"),
}
system_info = (
f"<code>• Bot uptime :</code> {currentTime}\n"
f"<code>• Sys uptime :</code> {osUptime}\n"
f"<code>• CPU usage :</code> {cpuUsage}%\n"
f"<code>• Bot uptime :</code> {current_time}\n"
f"<code>• Sys uptime :</code> {os_uptime}\n"
f"<code>• CPU usage :</code> {cpu_usage}%\n"
f"<code>• RAM usage :</code> {memory.percent}%\n"
f"<code>• Disk usage :</code> {disk}%\n"
f"<code>• Free space :</code> {get_readable_file_size(free)}\n"
Expand Down Expand Up @@ -222,7 +222,7 @@ async def ping(_, message):


@new_task
async def AeonCallback(_, query):
async def aeon_callback(_, query):
message = query.message
user_id = query.from_user.id
data = query.data.split()
Expand All @@ -231,27 +231,27 @@ async def AeonCallback(_, query):
if data[2] == "logdisplay":
await query.answer()
async with aiopen("log.txt", "r") as f:
logFileLines = (await f.read()).splitlines()
log_file_lines = (await f.read()).splitlines()

def parseline(line):
try:
return "[" + line.split("] [", 1)[1]
except IndexError:
return line

ind, Loglines = 1, ""
ind, log_lines = 1, ""
try:
while len(Loglines) <= 3500:
Loglines = parseline(logFileLines[-ind]) + "\n" + Loglines
if ind == len(logFileLines):
while len(log_lines) <= 3500:
log_lines = parseline(log_file_lines[-ind]) + "\n" + log_lines
if ind == len(log_file_lines):
break
ind += 1
startLine = "<pre language='python'>"
endLine = "</pre>"
start_line = "<pre language='python'>"
end_line = "</pre>"
btn = ButtonMaker()
btn.callback("Close", f"aeon {user_id} close")
reply_message = await send_message(
message, startLine + escape(Loglines) + endLine, btn.column(1)
message, start_line + escape(log_lines) + end_line, btn.column(1)
)
await query.edit_message_reply_markup(None)
await delete_message(message)
Expand Down Expand Up @@ -330,7 +330,7 @@ async def main():
filters=command(BotCommands.StatsCommand) & CustomFilters.authorized,
)
)
bot.add_handler(CallbackQueryHandler(AeonCallback, filters=regex(r"^aeon")))
bot.add_handler(CallbackQueryHandler(aeon_callback, filters=regex(r"^aeon")))
LOGGER.info("Bot Started!")
signal(SIGINT, exit_clean_up)

Expand Down
16 changes: 8 additions & 8 deletions bot/helper/aeon_utils/nsfw_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
]


def isNSFW(text):
def is_nsfw(text):
pattern = (
r"(?:^|\W|_)(?:"
+ "|".join(escape(keyword) for keyword in nsfw_keywords)
Expand All @@ -39,30 +39,30 @@ def isNSFW(text):
return bool(search(pattern, text, flags=IGNORECASE))


def isNSFWdata(data):
def is_nsfw_data(data):
if isinstance(data, list):
for item in data:
if isinstance(item, dict):
if any(
isinstance(value, str) and isNSFW(value)
isinstance(value, str) and is_nsfw(value)
for value in item.values()
):
return True
elif (
"name" in item
and isinstance(item["name"], str)
and isNSFW(item["name"])
and is_nsfw(item["name"])
):
return True
elif isinstance(data, dict) and "contents" in data:
for item in data["contents"]:
if "filename" in item and isNSFW(item["filename"]):
if "filename" in item and is_nsfw(item["filename"]):
return True
return False


async def nsfw_precheck(message):
if isNSFW(message.text):
if is_nsfw(message.text):
return True

reply_to = message.reply_to_message
Expand All @@ -72,11 +72,11 @@ async def nsfw_precheck(message):
for attr in ["document", "video"]:
if hasattr(reply_to, attr) and getattr(reply_to, attr):
file_name = getattr(reply_to, attr).file_name
if file_name and isNSFW(file_name):
if file_name and is_nsfw(file_name):
return True

return any(
isNSFW(getattr(reply_to, attr))
is_nsfw(getattr(reply_to, attr))
for attr in ["caption", "text"]
if hasattr(reply_to, attr) and getattr(reply_to, attr)
)
28 changes: 14 additions & 14 deletions bot/helper/ext_utils/bot_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
bot_name,
user_data,
config_dict,
botStartTime,
bot_start_time,
download_dict,
extra_buttons,
download_dict_lock,
Expand Down Expand Up @@ -123,7 +123,7 @@ class MirrorStatus:
STATUS_PROCESSING = "Processing"


class setInterval:
class SetInterval:
def __init__(self, interval, action):
self.interval = interval
self.action = action
Expand All @@ -138,7 +138,7 @@ def cancel(self):
self.task.cancel()


def isMkv(file):
def is_mkv(file):
return file.lower().endswith("mkv")


Expand All @@ -156,7 +156,7 @@ def get_readable_file_size(size_in_bytes: int):
)


async def getDownloadByGid(gid):
async def get_task_by_gid(gid):
async with download_dict_lock:
return next(
(
Expand All @@ -168,7 +168,7 @@ async def getDownloadByGid(gid):
)


async def getAllDownload(req_status, user_id=None):
async def get_all_task(req_status, user_id=None):
dls = []
async with download_dict_lock:
for dl in list(download_dict.values()):
Expand All @@ -181,7 +181,7 @@ async def getAllDownload(req_status, user_id=None):


async def get_user_tasks(user_id, maxtask):
if tasks := await getAllDownload("all", user_id):
if tasks := await get_all_task("all", user_id):
return len(tasks) >= maxtask
return None

Expand Down Expand Up @@ -211,7 +211,7 @@ async def get_telegraph_list(telegraph_content):
return buttons.column(1)


def handleIndex(index, dic):
def handle_index(index, dic):
while True:
if abs(index) < len(dic):
break
Expand All @@ -233,9 +233,9 @@ def progress_bar(pct):
if isinstance(pct, str):
pct = float(pct.strip("%"))
p = min(max(pct, 0), 100)
cFull = int((p + 5) // 10)
p_str = "●" * cFull
p_str += "○" * (10 - cFull)
c_full = int((p + 5) // 10)
p_str = "●" * c_full
p_str += "○" * (10 - c_full)
return p_str


Expand All @@ -251,7 +251,7 @@ def get_readable_message():
msg = "<b>Powered by Aeon</b>\n\n"
button = None
tasks = len(download_dict)
currentTime = get_readable_time(time() - botStartTime)
current_time = get_readable_time(time() - bot_start_time)
if config_dict["BOT_MAX_TASKS"]:
bmax_task = f"/{config_dict['BOT_MAX_TASKS']}"
else:
Expand Down Expand Up @@ -296,7 +296,7 @@ def get_readable_message():
buttons.callback("Next", "status nex")
button = buttons.column(3)
msg += f"<b>• Tasks</b>: {tasks}{bmax_task}"
msg += f"\n<b>• Bot uptime</b>: {currentTime}"
msg += f"\n<b>• Bot uptime</b>: {current_time}"
msg += f"\n<b>• Free disk space</b>: {get_readable_file_size(disk_usage('/usr/src/app/downloads/').free)}"
return msg, button

Expand Down Expand Up @@ -525,10 +525,10 @@ async def checking_access(user_id, button=None):
if DATABASE_URL:
data["time"] = await DbManager().get_token_expiry(user_id)
expire = data.get("time")
isExpired = (
is_expired = (
expire is None or expire is not None and (time() - expire) > token_timeout
)
if isExpired:
if is_expired:
token = data["token"] if expire is None and "token" in data else str(uuid4())
if expire is not None:
del data["time"]
Expand Down
4 changes: 2 additions & 2 deletions bot/helper/ext_utils/files_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
from bot.modules.mediainfo import parseinfo
from bot.helper.aeon_utils.metadata import change_metadata
from bot.helper.ext_utils.bot_utils import (
isMkv,
is_mkv,
cmd_exec,
sync_to_async,
get_readable_time,
Expand Down Expand Up @@ -446,7 +446,7 @@ async def process_file(file_, user_id, dirpath=None, isMirror=False):
metadata_key = user_dict.get("metadata", "") or config_dict["METADATA_KEY"]
prefile_ = file_

if metadata_key and dirpath and isMkv(file_):
if metadata_key and dirpath and is_mkv(file_):
file_ = await change_metadata(file_, dirpath, metadata_key)

file_ = re_sub(r"^www\S+\s*[-_]*\s*", "", file_)
Expand Down
22 changes: 11 additions & 11 deletions bot/helper/listeners/aria2_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from bot.helper.ext_utils.bot_utils import (
new_thread,
sync_to_async,
getDownloadByGid,
get_task_by_gid,
get_telegraph_list,
bt_selection_buttons,
)
Expand All @@ -33,7 +33,7 @@ async def __onDownloadStarted(api, gid):
if download.is_metadata:
LOGGER.info(f"onDownloadStarted: {gid} METADATA")
await sleep(1)
if dl := await getDownloadByGid(gid):
if dl := await get_task_by_gid(gid):
listener = dl.listener()
if listener.select:
metamsg = "Downloading Metadata, wait then you can select files. Use torrent file to avoid this wait."
Expand All @@ -50,7 +50,7 @@ async def __onDownloadStarted(api, gid):
if config_dict["STOP_DUPLICATE"]:
await sleep(1)
if dl is None:
dl = await getDownloadByGid(gid)
dl = await get_task_by_gid(gid)
if dl:
if not hasattr(dl, "listener"):
LOGGER.warning(
Expand Down Expand Up @@ -91,7 +91,7 @@ async def __onDownloadStarted(api, gid):
return
await sleep(1)
if dl is None:
dl = await getDownloadByGid(gid)
dl = await get_task_by_gid(gid)
if dl is not None:
if not hasattr(dl, "listener"):
LOGGER.warning(
Expand Down Expand Up @@ -133,7 +133,7 @@ async def __onDownloadComplete(api, gid):
if download.followed_by_ids:
new_gid = download.followed_by_ids[0]
LOGGER.info(f"Gid changed from {gid} to {new_gid}")
if dl := await getDownloadByGid(new_gid):
if dl := await get_task_by_gid(new_gid):
listener = dl.listener()
if config_dict["BASE_URL"] and listener.select:
if not dl.queued:
Expand All @@ -143,7 +143,7 @@ async def __onDownloadComplete(api, gid):
await send_message(listener.message, msg, SBUTTONS)
elif download.is_torrent:
if (
(dl := await getDownloadByGid(gid))
(dl := await get_task_by_gid(gid))
and hasattr(dl, "listener")
and dl.seeding
):
Expand All @@ -155,7 +155,7 @@ async def __onDownloadComplete(api, gid):
await sync_to_async(api.remove, [download], force=True, files=True)
else:
LOGGER.info(f"onDownloadComplete: {download.name} - Gid: {gid}")
if dl := await getDownloadByGid(gid):
if dl := await get_task_by_gid(gid):
listener = dl.listener()
await listener.onDownloadComplete()
await sync_to_async(api.remove, [download], force=True, files=True)
Expand All @@ -169,7 +169,7 @@ async def __onBtDownloadComplete(api, gid):
if download.options.follow_torrent == "false":
return
LOGGER.info(f"onBtDownloadComplete: {download.name} - Gid: {gid}")
if dl := await getDownloadByGid(gid):
if dl := await get_task_by_gid(gid):
listener = dl.listener()
if listener.select:
res = download.files
Expand Down Expand Up @@ -197,7 +197,7 @@ async def __onBtDownloadComplete(api, gid):
download = download.live
if listener.seed:
if download.is_complete:
if dl := await getDownloadByGid(gid):
if dl := await get_task_by_gid(gid):
LOGGER.info(f"Cancelling Seed: {download.name}")
await listener.onUploadError(
f"Seeding stopped with Ratio: {dl.ratio()} and Time: {dl.seeding_time()}"
Expand All @@ -223,7 +223,7 @@ async def __onBtDownloadComplete(api, gid):
@new_thread
async def __onDownloadStopped(_, gid):
await sleep(6)
if dl := await getDownloadByGid(gid):
if dl := await get_task_by_gid(gid):
listener = dl.listener()
await listener.onDownloadError("Dead torrent!")

Expand All @@ -240,7 +240,7 @@ async def __onDownloadError(api, gid):
LOGGER.info(f"Download Error: {error}")
except Exception:
pass
if dl := await getDownloadByGid(gid):
if dl := await get_task_by_gid(gid):
listener = dl.listener()
await listener.onDownloadError(error)

Expand Down
Loading

0 comments on commit 88a466e

Please sign in to comment.