Add optional status limit with buttons

-Minor changes
Note: I recommend limit status to 4 tasks max

Signed-off-by: anas <e.anastayyar@gmail.com>
This commit is contained in:
anas 2021-07-16 11:43:21 +03:00
parent a6c5fe62af
commit c6c4239cc2
7 changed files with 123 additions and 51 deletions

View File

@ -158,6 +158,14 @@ telegraph = Telegraph()
telegraph.create_account(short_name=sname)
telegraph_token = telegraph.get_access_token()
try:
STATUS_LIMIT = getConfig('STATUS_LIMIT')
if len(STATUS_LIMIT) == 0:
raise KeyError
else:
STATUS_LIMIT = int(getConfig('STATUS_LIMIT'))
except KeyError:
STATUS_LIMIT = None
try:
MEGA_API_KEY = getConfig('MEGA_API_KEY')
except KeyError:

View File

@ -2,9 +2,13 @@ import logging
import re
import threading
import time
import math
from bot.helper.telegram_helper.bot_commands import BotCommands
from bot import download_dict, download_dict_lock, FINISHED_PROGRESS_STR, UNFINISHED_PROGRESS_STR
from bot import dispatcher, download_dict, download_dict_lock, FINISHED_PROGRESS_STR, UNFINISHED_PROGRESS_STR, STATUS_LIMIT
from telegram import InlineKeyboardMarkup
from telegram.ext import CallbackQueryHandler
from bot.helper.telegram_helper import button_build, message_utils
LOGGER = logging.getLogger(__name__)
@ -12,6 +16,9 @@ MAGNET_REGEX = r"magnet:\?xt=urn:btih:[a-zA-Z0-9]*"
URL_REGEX = r"(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+"
COUNT = 0
PAGE_NO = 1
class MirrorStatus:
STATUS_UPLOADING = "Uploading...📤"
@ -99,29 +106,71 @@ def get_progress_bar_string(status):
def get_readable_message():
with download_dict_lock:
msg = ""
INDEX = 0
if STATUS_LIMIT is not None:
dick_no = len(download_dict)
global pages
pages = math.ceil(dick_no/STATUS_LIMIT)
if PAGE_NO > pages and pages != 0:
globals()['COUNT'] -= STATUS_LIMIT
globals()['PAGE_NO'] -= 1
for download in list(download_dict.values()):
msg += f"<b>Filename:</b> <code>{download.name()}</code>"
msg += f"\n<b>Status:</b> <i>{download.status()}</i>"
if download.status() != MirrorStatus.STATUS_ARCHIVING and download.status() != MirrorStatus.STATUS_EXTRACTING:
msg += f"\n<code>{get_progress_bar_string(download)} {download.progress()}</code>"
INDEX += 1
if INDEX > COUNT:
msg += f"<b>Filename:</b> <code>{download.name()}</code>"
msg += f"\n<b>Status:</b> <i>{download.status()}</i>"
if download.status() != MirrorStatus.STATUS_ARCHIVING and download.status() != MirrorStatus.STATUS_EXTRACTING:
msg += f"\n<code>{get_progress_bar_string(download)} {download.progress()}</code>"
if download.status() == MirrorStatus.STATUS_DOWNLOADING:
msg += f"\n<b>Downloaded:</b> {get_readable_file_size(download.processed_bytes())} of {download.size()}"
else:
msg += f"\n<b>Uploaded:</b> {get_readable_file_size(download.processed_bytes())} of {download.size()}"
msg += f"\n<b>Speed:</b> {download.speed()}" \
f", <b>ETA:</b> {download.eta()} "
# if hasattr(download, 'is_torrent'):
try:
msg += f"\n<b>Seeders:</b> {download.aria_download().num_seeders}" \
f" | <b>Peers:</b> {download.aria_download().connections}"
except:
pass
msg += f'\n<b>User:</b> <a href="tg://user?id={download.message.from_user.id}">{download.message.from_user.first_name}</a> (<code>{download.message.from_user.id}</code>)'
if download.status() == MirrorStatus.STATUS_DOWNLOADING:
msg += f"\n<b>Downloaded:</b> {get_readable_file_size(download.processed_bytes())} of {download.size()}"
else:
msg += f"\n<b>Uploaded:</b> {get_readable_file_size(download.processed_bytes())} of {download.size()}"
msg += f"\n<b>Speed:</b> {download.speed()}" \
f", <b>ETA:</b> {download.eta()} "
# if hasattr(download, 'is_torrent'):
try:
msg += f"\n<b>Seeders:</b> {download.aria_download().num_seeders}" \
f" | <b>Peers:</b> {download.aria_download().connections}"
except:
pass
msg += f'\n<b>User:</b> <a href="tg://user?id={download.message.from_user.id}">{download.message.from_user.first_name}</a> (<code>{download.message.from_user.id}</code>)'
if download.status() == MirrorStatus.STATUS_DOWNLOADING:
msg += f"\n<b>To Stop:</b> <code>/{BotCommands.CancelMirror} {download.gid()}</code>"
msg += "\n\n"
return msg
msg += f"\n<b>To Stop:</b> <code>/{BotCommands.CancelMirror} {download.gid()}</code>"
msg += "\n\n"
if STATUS_LIMIT is not None:
limit = COUNT + STATUS_LIMIT
if INDEX >= limit:
break
if STATUS_LIMIT is not None:
if INDEX > limit:
return None, None
msg += f"Page: {PAGE_NO}/{pages} | Tasks: {dick_no}\n"
buttons = button_build.ButtonMaker()
buttons.sbutton("Previous", "pre")
buttons.sbutton("Next", "nex")
button = InlineKeyboardMarkup(buttons.build_menu(2))
return msg, button
return msg, ""
def flip(update, context):
query = update.callback_query
query.answer()
global COUNT, PAGE_NO
if query.data == "nex":
if PAGE_NO == pages:
COUNT = 0
PAGE_NO = 1
else:
COUNT += STATUS_LIMIT
PAGE_NO += 1
elif query.data == "pre":
if PAGE_NO == 1:
COUNT = STATUS_LIMIT * (pages - 1)
PAGE_NO = pages
else:
COUNT -= STATUS_LIMIT
PAGE_NO -= 1
message_utils.update_all_messages()
def get_readable_time(seconds: int) -> str:
result = ''
@ -180,3 +229,8 @@ def new_thread(fn):
return thread
return wrapper
next_handler = CallbackQueryHandler(flip, pattern="nex", run_async=True)
previous_handler = CallbackQueryHandler(flip, pattern="pre", run_async=True)
dispatcher.add_handler(next_handler)
dispatcher.add_handler(previous_handler)

View File

@ -61,7 +61,7 @@ class AriaDownloadHelper(DownloadHelper):
dl.getListener().onDownloadError(f'{mssg}.\nYour File/Folder size is {get_readable_file_size(size)}')
aria2.remove([download], force=True)
return
update_all_messages()
update_all_messages()
def __onDownloadComplete(self, api: API, gid):
dl = getDownloadByGid(gid)
@ -83,13 +83,14 @@ class AriaDownloadHelper(DownloadHelper):
@new_thread
def __onDownloadStopped(self, api, gid):
sleep(0.5)
sleep(4)
dl = getDownloadByGid(gid)
if dl:
dl.getListener().onDownloadError('Dead torrent!')
@new_thread
def __onDownloadError(self, api, gid):
LOGGER.info(f"onDownloadError: {gid}")
sleep(0.5) # sleep for split second to ensure proper dl gid update from onDownloadComplete
dl = getDownloadByGid(gid)
download = aria2.get_download(gid)

View File

@ -1,16 +1,20 @@
from telegram import InlineKeyboardButton
class ButtonMaker:
def __init__(self):
self.button = []
def __init__(self):
self.button = []
def buildbutton(self, key, link):
self.button.append(InlineKeyboardButton(text = key, url = link))
def buildbutton(self, key, link):
self.button.append(InlineKeyboardButton(text = key, url = link))
def build_menu(self, n_cols, footer_buttons=None, header_buttons=None):
menu = [self.button[i:i + n_cols] for i in range(0, len(self.button), n_cols)]
if header_buttons:
menu.insert(0, header_buttons)
if footer_buttons:
menu.append(footer_buttons)
return menu
def sbutton(self, key, data):
self.button.append(InlineKeyboardButton(text = key, callback_data = data))
def build_menu(self, n_cols, footer_buttons=None, header_buttons=None):
menu = [self.button[i:i + n_cols] for i in range(0, len(self.button), n_cols)]
if header_buttons:
menu.insert(0, header_buttons)
if footer_buttons:
menu.append(footer_buttons)
return menu

View File

@ -70,7 +70,9 @@ def update_all_messages():
total, used, free = shutil.disk_usage('.')
free = get_readable_file_size(free)
currentTime = get_readable_time(time.time() - botStartTime)
msg = get_readable_message()
msg, buttons = get_readable_message()
if msg is None:
return
msg += f"<b>CPU:</b> {psutil.cpu_percent()}%" \
f" <b>RAM:</b> {psutil.virtual_memory().percent}%" \
f" <b>DISK:</b> {psutil.disk_usage('/').percent}%"
@ -95,10 +97,11 @@ def update_all_messages():
with status_reply_dict_lock:
for chat_id in list(status_reply_dict.keys()):
if status_reply_dict[chat_id] and msg != status_reply_dict[chat_id].text:
if len(msg) == 0:
msg = "Starting DL"
try:
editMessage(msg, status_reply_dict[chat_id])
if buttons == "":
editMessage(msg, status_reply_dict[chat_id])
else:
editMessage(msg, status_reply_dict[chat_id], buttons)
except Exception as e:
LOGGER.error(str(e))
status_reply_dict[chat_id].text = msg
@ -108,7 +111,9 @@ def sendStatusMessage(msg, bot):
total, used, free = shutil.disk_usage('.')
free = get_readable_file_size(free)
currentTime = get_readable_time(time.time() - botStartTime)
progress = get_readable_message()
progress, buttons = get_readable_message()
if progress is None:
progress, buttons = get_readable_message()
progress += f"<b>CPU:</b> {psutil.cpu_percent()}%" \
f" <b>RAM:</b> {psutil.virtual_memory().percent}%" \
f" <b>DISK:</b> {psutil.disk_usage('/').percent}%"
@ -140,7 +145,8 @@ def sendStatusMessage(msg, bot):
LOGGER.error(str(e))
del status_reply_dict[msg.message.chat.id]
pass
if len(progress) == 0:
progress = "Starting DL"
message = sendMessage(progress, bot, msg)
if buttons == "":
message = sendMessage(progress, bot, msg)
else:
message = sendMarkup(progress, bot, msg, buttons)
status_reply_dict[msg.message.chat.id] = message

View File

@ -1,8 +1,6 @@
from telegram.ext import CommandHandler
from bot import dispatcher, status_reply_dict, DOWNLOAD_STATUS_UPDATE_INTERVAL, status_reply_dict_lock
from bot import dispatcher, status_reply_dict, status_reply_dict_lock, download_dict, download_dict_lock
from bot.helper.telegram_helper.message_utils import *
from time import sleep
from bot.helper.ext_utils.bot_utils import get_readable_message
from telegram.error import BadRequest
from bot.helper.telegram_helper.filters import CustomFilters
from bot.helper.telegram_helper.bot_commands import BotCommands
@ -10,12 +8,12 @@ import threading
def mirror_status(update, context):
message = get_readable_message()
if len(message) == 0:
message = "No active downloads"
reply_message = sendMessage(message, context.bot, update)
threading.Thread(target=auto_delete_message, args=(bot, update.message, reply_message)).start()
return
with download_dict_lock:
if len(download_dict) == 0:
message = "No active downloads"
reply_message = sendMessage(message, context.bot, update)
threading.Thread(target=auto_delete_message, args=(bot, update.message, reply_message)).start()
return
index = update.effective_chat.id
with status_reply_dict_lock:
if index in status_reply_dict.keys():

View File

@ -20,6 +20,7 @@ SUDO_USERS = "" # Split by space
IGNORE_PENDING_REQUESTS = ""
USE_SERVICE_ACCOUNTS = ""
INDEX_URL = ""
STATUS_LIMIT = "" #recommend 4 max
UPTOBOX_TOKEN = ""
MEGA_API_KEY = ""
MEGA_EMAIL_ID = ""