Path: blob/master/bot/modules/mirror_leech.py
1626 views
from aiofiles.os import path as aiopath1from base64 import b64encode2from re import match as re_match34from .. import LOGGER, bot_loop, task_dict_lock, DOWNLOAD_DIR5from ..helper.ext_utils.bot_utils import (6get_content_type,7sync_to_async,8arg_parser,9COMMAND_USAGE,10)11from ..helper.ext_utils.exceptions import DirectDownloadLinkException12from ..helper.ext_utils.links_utils import (13is_url,14is_magnet,15is_gdrive_link,16is_rclone_path,17is_telegram_link,18is_gdrive_id,19)20from ..helper.listeners.task_listener import TaskListener21from ..helper.mirror_leech_utils.download_utils.aria2_download import (22add_aria2_download,23)24from ..helper.mirror_leech_utils.download_utils.direct_downloader import (25add_direct_download,26)27from ..helper.mirror_leech_utils.download_utils.direct_link_generator import (28direct_link_generator,29)30from ..helper.mirror_leech_utils.download_utils.gd_download import add_gd_download31from ..helper.mirror_leech_utils.download_utils.jd_download import add_jd_download32from ..helper.mirror_leech_utils.download_utils.qbit_download import add_qb_torrent33from ..helper.mirror_leech_utils.download_utils.nzb_downloader import add_nzb34from ..helper.mirror_leech_utils.download_utils.rclone_download import (35add_rclone_download,36)37from ..helper.mirror_leech_utils.download_utils.telegram_download import (38TelegramDownloadHelper,39)40from ..helper.telegram_helper.message_utils import send_message, get_tg_link_message414243class Mirror(TaskListener):44def __init__(45self,46client,47message,48is_qbit=False,49is_leech=False,50is_jd=False,51is_nzb=False,52same_dir=None,53bulk=None,54multi_tag=None,55options="",56):57if same_dir is None:58same_dir = {}59if bulk is None:60bulk = []61self.message = message62self.client = client63self.multi_tag = multi_tag64self.options = options65self.same_dir = same_dir66self.bulk = bulk67super().__init__()68self.is_qbit = is_qbit69self.is_leech = is_leech70self.is_jd = is_jd71self.is_nzb = is_nzb7273async def new_event(self):74text = self.message.text.split("\n")75input_list = text[0].split(" ")7677args = {78"-doc": False,79"-med": False,80"-d": False,81"-j": False,82"-s": False,83"-b": False,84"-e": False,85"-z": False,86"-sv": False,87"-ss": False,88"-f": False,89"-fd": False,90"-fu": False,91"-hl": False,92"-bt": False,93"-ut": False,94"-i": 0,95"-sp": 0,96"link": "",97"-n": "",98"-m": "",99"-up": "",100"-rcf": "",101"-au": "",102"-ap": "",103"-h": [],104"-t": "",105"-ca": "",106"-cv": "",107"-ns": "",108"-tl": "",109"-ff": set(),110}111112arg_parser(input_list[1:], args)113114self.select = args["-s"]115self.seed = args["-d"]116self.name = args["-n"]117self.up_dest = args["-up"]118self.rc_flags = args["-rcf"]119self.link = args["link"]120self.compress = args["-z"]121self.extract = args["-e"]122self.join = args["-j"]123self.thumb = args["-t"]124self.split_size = args["-sp"]125self.sample_video = args["-sv"]126self.screen_shots = args["-ss"]127self.force_run = args["-f"]128self.force_download = args["-fd"]129self.force_upload = args["-fu"]130self.convert_audio = args["-ca"]131self.convert_video = args["-cv"]132self.name_sub = args["-ns"]133self.hybrid_leech = args["-hl"]134self.thumbnail_layout = args["-tl"]135self.as_doc = args["-doc"]136self.as_med = args["-med"]137self.folder_name = f"/{args["-m"]}".rstrip("/") if len(args["-m"]) > 0 else ""138self.bot_trans = args["-bt"]139self.user_trans = args["-ut"]140self.ffmpeg_cmds = args["-ff"]141142headers = args["-h"]143if headers:144headers = headers.split("|")145is_bulk = args["-b"]146147bulk_start = 0148bulk_end = 0149ratio = None150seed_time = None151reply_to = None152file_ = None153session = ""154155try:156self.multi = int(args["-i"])157except:158self.multi = 0159160if not isinstance(self.seed, bool):161dargs = self.seed.split(":")162ratio = dargs[0] or None163if len(dargs) == 2:164seed_time = dargs[1] or None165self.seed = True166167if not isinstance(is_bulk, bool):168dargs = is_bulk.split(":")169bulk_start = dargs[0] or "0"170if len(dargs) == 2:171bulk_end = dargs[1] or "0"172is_bulk = True173174if not is_bulk:175if self.multi > 0:176if self.folder_name:177async with task_dict_lock:178if self.folder_name in self.same_dir:179self.same_dir[self.folder_name]["tasks"].add(self.mid)180for fd_name in self.same_dir:181if fd_name != self.folder_name:182self.same_dir[fd_name]["total"] -= 1183elif self.same_dir:184self.same_dir[self.folder_name] = {185"total": self.multi,186"tasks": {self.mid},187}188for fd_name in self.same_dir:189if fd_name != self.folder_name:190self.same_dir[fd_name]["total"] -= 1191else:192self.same_dir = {193self.folder_name: {194"total": self.multi,195"tasks": {self.mid},196}197}198elif self.same_dir:199async with task_dict_lock:200for fd_name in self.same_dir:201self.same_dir[fd_name]["total"] -= 1202else:203await self.init_bulk(input_list, bulk_start, bulk_end, Mirror)204return205206if len(self.bulk) != 0:207del self.bulk[0]208209await self.run_multi(input_list, Mirror)210211await self.get_tag(text)212213path = f"{DOWNLOAD_DIR}{self.mid}{self.folder_name}"214215if not self.link and (reply_to := self.message.reply_to_message):216if reply_to.text:217self.link = reply_to.text.split("\n", 1)[0].strip()218if is_telegram_link(self.link):219try:220reply_to, session = await get_tg_link_message(self.link)221except Exception as e:222await send_message(self.message, f"ERROR: {e}")223await self.remove_from_same_dir()224return225226if isinstance(reply_to, list):227self.bulk = reply_to228b_msg = input_list[:1]229self.options = " ".join(input_list[1:])230b_msg.append(f"{self.bulk[0]} -i {len(self.bulk)} {self.options}")231nextmsg = await send_message(self.message, " ".join(b_msg))232nextmsg = await self.client.get_messages(233chat_id=self.message.chat.id, message_ids=nextmsg.id234)235if self.message.from_user:236nextmsg.from_user = self.user237else:238nextmsg.sender_chat = self.user239await Mirror(240self.client,241nextmsg,242self.is_qbit,243self.is_leech,244self.is_jd,245self.is_nzb,246self.same_dir,247self.bulk,248self.multi_tag,249self.options,250).new_event()251return252253if reply_to:254file_ = (255reply_to.document256or reply_to.photo257or reply_to.video258or reply_to.audio259or reply_to.voice260or reply_to.video_note261or reply_to.sticker262or reply_to.animation263or None264)265266if file_ is None:267if reply_text := reply_to.text:268self.link = reply_text.split("\n", 1)[0].strip()269else:270reply_to = None271elif reply_to.document and (272file_.mime_type == "application/x-bittorrent"273or file_.file_name.endswith((".torrent", ".dlc", ".nzb"))274):275self.link = await reply_to.download()276file_ = None277278if (279not self.link280and file_ is None281or is_telegram_link(self.link)282and reply_to is None283or file_ is None284and not is_url(self.link)285and not is_magnet(self.link)286and not await aiopath.exists(self.link)287and not is_rclone_path(self.link)288and not is_gdrive_id(self.link)289and not is_gdrive_link(self.link)290):291await send_message(292self.message, COMMAND_USAGE["mirror"][0], COMMAND_USAGE["mirror"][1]293)294await self.remove_from_same_dir()295return296297if len(self.link) > 0:298LOGGER.info(self.link)299300try:301await self.before_start()302except Exception as e:303await send_message(self.message, e)304await self.remove_from_same_dir()305return306307if (308not self.is_jd309and not self.is_nzb310and not self.is_qbit311and not is_magnet(self.link)312and not is_rclone_path(self.link)313and not is_gdrive_link(self.link)314and not self.link.endswith(".torrent")315and file_ is None316and not is_gdrive_id(self.link)317):318content_type = await get_content_type(self.link)319if content_type is None or re_match(r"text/html|text/plain", content_type):320try:321self.link = await sync_to_async(direct_link_generator, self.link)322if isinstance(self.link, tuple):323self.link, headers = self.link324elif isinstance(self.link, str):325LOGGER.info(f"Generated link: {self.link}")326except DirectDownloadLinkException as e:327e = str(e)328if "This link requires a password!" not in e:329LOGGER.info(e)330if e.startswith("ERROR:"):331await send_message(self.message, e)332await self.remove_from_same_dir()333return334except Exception as e:335await send_message(self.message, e)336await self.remove_from_same_dir()337return338339if file_ is not None:340await TelegramDownloadHelper(self).add_download(341reply_to, f"{path}/", session342)343elif isinstance(self.link, dict):344await add_direct_download(self, path)345elif self.is_jd:346await add_jd_download(self, path)347elif self.is_qbit:348await add_qb_torrent(self, path, ratio, seed_time)349elif self.is_nzb:350await add_nzb(self, path)351elif is_rclone_path(self.link):352await add_rclone_download(self, f"{path}/")353elif is_gdrive_link(self.link) or is_gdrive_id(self.link):354await add_gd_download(self, path)355else:356ussr = args["-au"]357pssw = args["-ap"]358if ussr or pssw:359auth = f"{ussr}:{pssw}"360headers.extend(361[f"authorization: Basic {b64encode(auth.encode()).decode('ascii')}"]362)363await add_aria2_download(self, path, headers, ratio, seed_time)364365366async def mirror(client, message):367bot_loop.create_task(Mirror(client, message).new_event())368369370async def qb_mirror(client, message):371bot_loop.create_task(Mirror(client, message, is_qbit=True).new_event())372373374async def jd_mirror(client, message):375bot_loop.create_task(Mirror(client, message, is_jd=True).new_event())376377378async def nzb_mirror(client, message):379bot_loop.create_task(Mirror(client, message, is_nzb=True).new_event())380381382async def leech(client, message):383bot_loop.create_task(Mirror(client, message, is_leech=True).new_event())384385386async def qb_leech(client, message):387bot_loop.create_task(388Mirror(client, message, is_qbit=True, is_leech=True).new_event()389)390391392async def jd_leech(client, message):393bot_loop.create_task(Mirror(client, message, is_leech=True, is_jd=True).new_event())394395396async def nzb_leech(client, message):397bot_loop.create_task(398Mirror(client, message, is_leech=True, is_nzb=True).new_event()399)400401402