Skip to content

Commit

Permalink
fix qbmirror
Browse files Browse the repository at this point in the history
  • Loading branch information
weebzone committed Sep 20, 2022
1 parent 25b345e commit e13f9ad
Show file tree
Hide file tree
Showing 6 changed files with 57 additions and 25 deletions.
2 changes: 1 addition & 1 deletion bot/helper/ext_utils/bot_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def get_readable_message():
else:
msg += f"\n<b>├ Engine :</b> {download.eng()}"
msg += f"\n<b>╰ Size: </b>{download.size()}"
msg += f"\n<b>_____________________________________</b>"
msg += f"\n<b>_________________________________</b>"
msg += "\n\n"
if STATUS_LIMIT is not None and index == STATUS_LIMIT:
break
Expand Down
62 changes: 47 additions & 15 deletions bot/helper/mirror_utils/download_utils/qbit_downloader.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
from hashlib import sha1
from base64 import b16encode, b32decode
from bencoding import bencode, bdecode
from time import sleep, time
from re import search as re_search
from os import remove
from os import path as ospath, listdir
from time import sleep, time
from re import search as re_search
Expand Down Expand Up @@ -32,27 +38,40 @@ def __init__(self, listener):
def add_qb_torrent(self, link, path, ratio, seed_time):
self.__path = path
try:
op = self.client.torrents_add(link, save_path=path, tags=self.__listener.uid,
ratio_limit=ratio, seeding_time_limit=seed_time,
headers={'user-agent': 'Wget/1.12'})
if link.startswith('magnet:'):
self.ext_hash = _get_hash_magnet(link)
else:
self.ext_hash = _get_hash_file(link)
tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
if len(tor_info) > 0:
sendMessage("This Torrent already added!", self.__listener.bot, self.__listener.message)
return self.client.auth_log_out()
if link.startswith('magnet:'):
op = self.client.torrents_add(link, save_path=path, ratio_limit=ratio, seeding_time_limit=seed_time)
else:
op = self.client.torrents_add(torrent_files=[link], save_path=path, ratio_limit=ratio, seeding_time_limit=seed_time)
sleep(0.3)
if op.lower() == "ok.":
tor_info = self.client.torrents_info(tag=self.__listener.uid)
tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
if len(tor_info) == 0:
while True:
tor_info = self.client.torrents_info(tag=self.__listener.uid)
tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
if len(tor_info) > 0:
break
elif time() - self.__stalled_time >= 12:
self.client.torrents_delete_tags(tags=self.__listener.uid)
msg = "This Torrent already added or not a torrent. If something wrong please report."
elif time() - self.__stalled_time >= 30:
msg = "Not a torrent. If it's a torrent then report!"
self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
sendMessage(msg, self.__listener.bot, self.__listener.message)
self.client.auth_log_out()
return
if not link.startswith('magnet:'):
remove(link)
return self.client.auth_log_out()
if not link.startswith('magnet:'):
remove(link)
else:
sendMessage("This is an unsupported/invalid link.", self.__listener.bot, self.__listener.message)
self.client.auth_log_out()
return
if not link.startswith('magnet:'):
remove(link)
return self.client.auth_log_out()
tor_info = tor_info[0]
self.__name = tor_info.name
self.ext_hash = tor_info.hash
Expand Down Expand Up @@ -87,6 +106,7 @@ def add_qb_torrent(self, link, path, ratio, seed_time):
sendMessage(str(e), self.__listener.bot, self.__listener.message)
self.client.auth_log_out()


def __qb_listener(self):
try:
tor_info = self.client.torrents_info(torrent_hashes=self.ext_hash)
Expand Down Expand Up @@ -171,7 +191,7 @@ def __qb_listener(self):
self.__listener.onDownloadComplete()
if self.__listener.seed:
with download_dict_lock:
if self.__listener.uid not in list(download_dict.keys()):
if self.__listener.uid not in download_dict:
self.__remove_torrent()
return
download_dict[self.__listener.uid] = QbDownloadStatus(self.__listener, self)
Expand Down Expand Up @@ -200,7 +220,6 @@ def __onDownloadError(self, err):

def __remove_torrent(self):
self.client.torrents_delete(torrent_hashes=self.ext_hash, delete_files=True)
self.client.torrents_delete_tags(tags=self.__listener.uid)
self.client.auth_log_out()
self.__periodic.cancel()

Expand All @@ -209,4 +228,17 @@ def cancel_download(self):
LOGGER.info(f"Cancelling Seed: {self.__name}")
self.client.torrents_pause(torrent_hashes=self.ext_hash)
else:
self.__onDownloadError('Download stopped by user!')
self.__onDownloadError('Download stopped by user!')


def _get_hash_magnet(mgt: str):
hash_ = re_search(r'(?<=xt=urn:btih:)[a-zA-Z0-9]+', mgt).group(0)
if len(hash_) == 32:
hash_ = b16encode(b32decode(str(hash_))).decode()
return str(hash_)

def _get_hash_file(path):
with open(path, "rb") as f:
decodedDict = bdecode(f.read())
hash_ = sha1(bencode(decodedDict[b'info'])).hexdigest()
return str(hash_)
8 changes: 4 additions & 4 deletions bot/helper/mirror_utils/status_utils/qbit_download_status.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from bot import LOGGER
from bot.helper.ext_utils.bot_utils import MirrorStatus, get_readable_file_size, get_readable_time, EngineStatus

def get_download(client, uid):
def get_download(client, hash_):
try:
return client.torrents_info(tag=uid)[0]
return client.torrents_info(torrent_hashes=hash_)[0]
except Exception as e:
LOGGER.error(f'{e}: while getting torrent info')

Expand All @@ -14,11 +14,11 @@ def __init__(self, listener, obj):
self.__obj = obj
self.__listener = listener
self.__uid = listener.uid
self.__info = get_download(obj.client, self.__uid)
self.__info = get_download(obj.client, obj.ext_hash)
self.message = listener.message

def __update(self):
self.__info = get_download(self.__obj.client, self.__uid)
self.__info = get_download(self.__obj.client, self.__obj.ext_hash)

def progress(self):
"""
Expand Down
3 changes: 2 additions & 1 deletion bot/modules/bt_select.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from telegram.ext import CommandHandler, CallbackQueryHandler
from os import remove, path as ospath

from bot import aria2, BASE_URL, download_dict, dispatcher, download_dict_lock, SUDO_USERS, OWNER_ID
from bot.helper.telegram_helper.bot_commands import BotCommands
from bot.helper.telegram_helper.filters import CustomFilters
Expand Down Expand Up @@ -35,7 +36,7 @@ def select(update, context):
sendMessage("This task is not for you!", context.bot, update.message)
return
if dl.status() not in [MirrorStatus.STATUS_DOWNLOADING, MirrorStatus.STATUS_PAUSED, MirrorStatus.STATUS_WAITING]:
sendMessage('Task should be in downloading status or in pause status incase message deleted by wrong or in queued status incase you used torrent file!', context.bot, update.message)
sendMessage('Task should be in download or pause (incase message deleted by wrong) or queued (status incase you used torrent file)!', context.bot, update.message)
return
if dl.name().startswith('[METADATA]'):
sendMessage('Try after downloading metadata finished!', context.bot, update.message)
Expand Down
2 changes: 1 addition & 1 deletion bot/modules/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def onDownloadComplete(self):
with download_dict_lock:
download = download_dict[self.uid]
name = str(download.name()).replace('/', '')
gid = download.gid()
gid = download.gid()
LOGGER.info(f"Download completed: {name}")
if name == "None" or self.isQbit or not ospath.exists(f"{self.dir}/{name}"):
name = listdir(f"{self.dir}")[-1]
Expand Down
5 changes: 2 additions & 3 deletions bot/modules/mirror_leech.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,7 @@ def _mirror_leech(bot, message, isZip=False, extract=False, isQbit=False, isLeec
Thread(target=add_gd_download, args=(link, f'{DOWNLOAD_DIR}{listener.uid}', listener, is_gdtot, is_unified, is_udrive, name)).start()
elif is_mega_link(link):
Thread(target=add_mega_download, args=(link, f'{DOWNLOAD_DIR}{listener.uid}/', listener, name)).start()
elif isQbit:
elif isQbit and (is_magnet(link) or ospath.exists(link)):
Thread(target=QbDownloader(listener).add_qb_torrent, args=(link, f'{DOWNLOAD_DIR}{listener.uid}',
ratio, seed_time)).start()
else:
Expand All @@ -290,7 +290,7 @@ def _mirror_leech(bot, message, isZip=False, extract=False, isQbit=False, isLeec
else:
auth = ''
Thread(target=add_aria2c_download, args=(link, f'{DOWNLOAD_DIR}{listener.uid}', listener, name,
auth, ratio, seed_time)).start()
auth, ratio, seed_time)).start()

if multi > 1:
sleep(4)
Expand All @@ -305,7 +305,6 @@ def _mirror_leech(bot, message, isZip=False, extract=False, isQbit=False, isLeec




def mirror(update, context):
_mirror_leech(context.bot, update.message)

Expand Down

0 comments on commit e13f9ad

Please sign in to comment.