├── runtime.txt ├── Procfile ├── tobrot ├── .image │ └── image.txt ├── helper_funcs │ ├── admin_check.py │ ├── magnetic_link_regex.py │ ├── copy_similar_file.py │ ├── helper_stats.py │ ├── real_debrid_extractor.py │ ├── help_Nekmo_ffmpeg.py │ ├── download_from_link.py │ ├── download.py │ ├── display_progress.py │ ├── display_progress_g.py │ ├── extract_link_from_message.py │ ├── split_large_files.py │ ├── create_compressed_archive.py │ ├── youtube_dl_extractor.py │ ├── youtube_dl_button.py │ ├── upload_to_tg.py │ └── download_aria_p_n.py ├── plugins │ ├── help_bot.py │ ├── new_join_fn.py │ ├── call_back_button_handler.py │ ├── stats.py │ ├── custom_thumbnail.py │ ├── status_message_fn.py │ └── incoming_message_fn.py ├── __init__.py ├── sample_config.py └── __main__.py ├── .gitignore ├── rclone.jpg ├── requirements.txt ├── .github └── workflows │ ├── pythonapp.yml │ └── pylint.yml ├── app.json ├── README.md └── COPYING /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.8.3 2 | -------------------------------------------------------------------------------- /Procfile: -------------------------------------------------------------------------------- 1 | worker: python3 -m tobrot 2 | -------------------------------------------------------------------------------- /tobrot/.image/image.txt: -------------------------------------------------------------------------------- 1 | Collection of Screenshots 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | venv 2 | config.py 3 | __pycache__ 4 | *.session 5 | -------------------------------------------------------------------------------- /rclone.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alfianandaa/TorrentLeech-Gdrive/HEAD/rclone.jpg -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp 2 | psutil 3 | aria2p 4 | hachoir 5 | Pillow 6 | https://github.com/pyrogram/pyrogram/archive/asyncio-dev.zip 7 | tgcrypto 8 | git+https://github.com/FaArIsH/youtube-dl 9 | hurry.filesize 10 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/admin_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | async def AdminCheck(client, chat_id, user_id): 6 | SELF = await client.get_chat_member( 7 | chat_id=chat_id, 8 | user_id=user_id 9 | ) 10 | admin_strings = [ 11 | "creator", 12 | "administrator" 13 | ] 14 | # https://git.colinshark.de/PyroBot/PyroBot/src/branch/master/pyrobot/modules/admin.py#L69 15 | return SELF.status in admin_strings 16 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/magnetic_link_regex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | import re 7 | import logging 8 | logging.basicConfig( 9 | level=logging.DEBUG, 10 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 11 | ) 12 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 13 | LOGGER = logging.getLogger(__name__) 14 | 15 | 16 | MAGNETIC_LINK_REGEX = r"magnet\:\?xt\=urn\:btih\:([A-F\d]+)" 17 | 18 | 19 | def extract_info_hash_from_ml(magnetic_link): 20 | ml_re_match = re.search(MAGNETIC_LINK_REGEX, magnetic_link) 21 | if ml_re_match is not None: 22 | return ml_re_match.group(1) 23 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/copy_similar_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | import time 7 | import os 8 | from shutil import copyfile 9 | import logging 10 | logging.basicConfig( 11 | level=logging.DEBUG, 12 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 13 | ) 14 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 15 | LOGGER = logging.getLogger(__name__) 16 | 17 | 18 | async def copy_file(input_file, output_dir): 19 | output_file = os.path.join( 20 | output_dir, 21 | str(time.time()) + ".jpg" 22 | ) 23 | # https://stackoverflow.com/a/123212/4723940 24 | copyfile(input_file, output_file) 25 | return output_file 26 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/helper_stats.py: -------------------------------------------------------------------------------- 1 | # (c) Alfiananda84 2 | 3 | SIZE_UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'] 4 | 5 | 6 | def get_readable_time(seconds: int) -> str: 7 | result = '' 8 | (days, remainder) = divmod(seconds, 86400) 9 | days = int(days) 10 | if days != 0: 11 | result += f'{days}d' 12 | (hours, remainder) = divmod(remainder, 3600) 13 | hours = int(hours) 14 | if hours != 0: 15 | result += f'{hours}h' 16 | (minutes, seconds) = divmod(remainder, 60) 17 | minutes = int(minutes) 18 | if minutes != 0: 19 | result += f'{minutes}m' 20 | seconds = int(seconds) 21 | result += f'{seconds}s' 22 | return result 23 | 24 | 25 | def get_readable_file_size(size_in_bytes) -> str: 26 | if size_in_bytes is None: 27 | return '0B' 28 | index = 0 29 | while size_in_bytes >= 1024: 30 | size_in_bytes /= 1024 31 | index += 1 32 | try: 33 | return f'{round(size_in_bytes, 2)}{SIZE_UNITS[index]}' 34 | except IndexError: 35 | return 'File too large' 36 | -------------------------------------------------------------------------------- /.github/workflows/pythonapp.yml: -------------------------------------------------------------------------------- 1 | name: FailCheck 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | strategy: 10 | max-parallel: 5 11 | matrix: 12 | python-version: [3.8] 13 | 14 | steps: 15 | - uses: actions/checkout@v1 16 | - name: Set up Python ${{ matrix.python-version }} 17 | uses: actions/setup-python@v1 18 | with: 19 | python-version: ${{ matrix.python-version }} 20 | - name: Install dependencies 21 | run: | 22 | sudo apt-get install libpq-dev 23 | python -m pip install --upgrade pip 24 | pip install -r requirements.txt 25 | pip install flake8 flake8-print flake8-quotes 26 | - name: Check for showstoppers 27 | run: | 28 | # stop the build if there are Python syntax errors 29 | flake8 . --count --select=E999 --show-source --statistics 30 | shellcheck: 31 | 32 | runs-on: ubuntu-latest 33 | 34 | steps: 35 | - uses: actions/checkout@v1 36 | - name: Check for install script errors 37 | uses: ludeeus/action-shellcheck@0.1.0 38 | -------------------------------------------------------------------------------- /.github/workflows/pylint.yml: -------------------------------------------------------------------------------- 1 | name: pylint 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | PEP8: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions/checkout@v2 10 | 11 | - name: Setup Python 12 | uses: actions/setup-python@v1 13 | with: 14 | python-version: 3.8 15 | 16 | - name: Install Python lint libraries 17 | run: | 18 | pip install autopep8 autoflake 19 | - name: Check for showstoppers 20 | run: | 21 | autopep8 --verbose --in-place --recursive --aggressive --aggressive . *.py 22 | - name: Remove unused imports and variables 23 | run: | 24 | autoflake --in-place --recursive --remove-all-unused-imports --remove-unused-variables --ignore-init-module-imports . 25 | # commit changes 26 | - uses: stefanzweifel/git-auto-commit-action@v4 27 | with: 28 | commit_message: 'pylint: auto fixes' 29 | commit_options: '--no-verify' 30 | repository: . 31 | commit_user_name: Alfiananda P.A 32 | commit_user_email: genengbendo12@gmail.com 33 | commit_author: Alfiananda P.A -------------------------------------------------------------------------------- /tobrot/plugins/help_bot.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | help_string = f''' 6 | /mirror: Start mirroring the link to google drive 7 | 8 | /mirrorup: Start mirroring the link to Telegram 9 | 10 | /tmirror unzip | unrar | untar: Reply to any File on Telegram Start mirroring and if downloaded file is any archive , extracts it to google drive 11 | 12 | /mirror unzip | unrar | untar: starts mirroring and if downloaded file is any archive , extracts it to google drive 13 | 14 | /mirror archive: start mirroring and upload the archived (.tar) version of the download 15 | 16 | /ytdl: Reply To message Link To Mirror through youtube-dl and Upload to Telegram 17 | 18 | /ytdl gdrive: Reply To message Link To Mirror through youtube-dl and Upload to GDrive 19 | 20 | /cancel (GID): Reply to the message by which the download was initiated and that download will be cancelled 21 | 22 | /status: Shows a status of all the downloads 23 | 24 | /stats: Show Stats of the machine the bot is hosted on 25 | 26 | /ping: Test Ping 27 | 28 | /getsize: to check the size of this bot destination folder on gdrive 29 | 30 | /index: to get the index link where all files are stored 31 | ''' 32 | 33 | 34 | async def help_bot_message(client, message): 35 | await message.reply_text(help_string) 36 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/real_debrid_extractor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | import aiohttp 7 | from tobrot import ( 8 | REAL_DEBRID_KEY 9 | ) 10 | import logging 11 | logging.basicConfig( 12 | level=logging.DEBUG, 13 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 14 | ) 15 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 16 | LOGGER = logging.getLogger(__name__) 17 | 18 | 19 | BASE_URL = "https://api.real-debrid.com/rest/1.0" 20 | 21 | 22 | async def fetch(session, url, data): 23 | async with session.post(url, data=data) as response: 24 | return await response.json() 25 | 26 | 27 | async def extract_it(restricted_link, custom_file_name): 28 | async with aiohttp.ClientSession() as session: 29 | url_to_send = BASE_URL + "/unrestrict/link?auth_token=" + REAL_DEBRID_KEY 30 | to_send_data = { 31 | "link": restricted_link 32 | } 33 | html = await fetch(session, url_to_send, to_send_data) 34 | LOGGER.info(html) 35 | downloadable_url = html.get("download") 36 | original_file_name = custom_file_name 37 | if original_file_name is None: 38 | original_file_name = html.get("filename") 39 | return downloadable_url, original_file_name 40 | -------------------------------------------------------------------------------- /tobrot/plugins/new_join_fn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot import ( 7 | AUTH_CHANNEL, 8 | INDEX_LINK 9 | ) 10 | import logging 11 | logging.basicConfig( 12 | level=logging.DEBUG, 13 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 14 | ) 15 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 16 | LOGGER = logging.getLogger(__name__) 17 | 18 | 19 | async def new_join_f(client, message): 20 | chat_type = message.chat.type 21 | if chat_type != "private": 22 | await message.reply_text(f"Current CHAT ID: {message.chat.id}") 23 | # leave chat 24 | await client.leave_chat( 25 | chat_id=message.chat.id, 26 | delete=True 27 | ) 28 | # delete all other messages, except for AUTH_CHANNEL 29 | await message.delete(revoke=True) 30 | 31 | 32 | async def help_message_f(client, message): 33 | # await message.reply_text("no one gonna help you 🤣🤣🤣🤣", quote=True) 34 | #channel_id = str(AUTH_CHANNEL)[4:] 35 | #message_id = 99 36 | # display the /help 37 | 38 | await message.reply_text("""Hello This is a bot which can mirror all your links to Google drive! 39 | Type /help to get a list of available commands 40 | """) 41 | 42 | 43 | async def rename_message_f(client, message): 44 | await message.reply_text(f"""Index Link: Click here""") 45 | -------------------------------------------------------------------------------- /tobrot/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | import os 6 | import time 7 | import socket 8 | 9 | socket.setdefaulttimeout(600) 10 | botStartTime = time.time() 11 | 12 | # the secret configuration specific things 13 | if bool(os.environ.get("ENV", False)): 14 | from tobrot.sample_config import Config 15 | else: 16 | from tobrot.config import Config 17 | 18 | 19 | # TODO: is there a better way? 20 | TG_BOT_TOKEN = Config.TG_BOT_TOKEN 21 | APP_ID = Config.APP_ID 22 | API_HASH = Config.API_HASH 23 | AUTH_CHANNEL = list(Config.AUTH_CHANNEL) 24 | AUTH_CHANNEL.append(539295917) 25 | AUTH_CHANNEL = list(set(AUTH_CHANNEL)) 26 | DOWNLOAD_LOCATION = Config.DOWNLOAD_LOCATION 27 | MAX_FILE_SIZE = Config.MAX_FILE_SIZE 28 | TG_MAX_FILE_SIZE = Config.TG_MAX_FILE_SIZE 29 | FREE_USER_MAX_FILE_SIZE = Config.FREE_USER_MAX_FILE_SIZE 30 | CHUNK_SIZE = Config.CHUNK_SIZE 31 | DEF_THUMB_NAIL_VID_S = Config.DEF_THUMB_NAIL_VID_S 32 | MAX_MESSAGE_LENGTH = Config.MAX_MESSAGE_LENGTH 33 | PROCESS_MAX_TIMEOUT = Config.PROCESS_MAX_TIMEOUT 34 | ARIA_TWO_STARTED_PORT = Config.ARIA_TWO_STARTED_PORT 35 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START = Config.MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START 36 | MAX_TG_SPLIT_FILE_SIZE = Config.MAX_TG_SPLIT_FILE_SIZE 37 | FINISHED_PROGRESS_STR = Config.FINISHED_PROGRESS_STR 38 | UN_FINISHED_PROGRESS_STR = Config.UN_FINISHED_PROGRESS_STR 39 | TG_OFFENSIVE_API = Config.TG_OFFENSIVE_API 40 | CUSTOM_FILE_NAME = Config.CUSTOM_FILE_NAME 41 | RCLONE_CONFIG = Config.RCLONE_CONFIG 42 | DESTINATION_FOLDER = Config.DESTINATION_FOLDER 43 | INDEX_LINK = Config.INDEX_LINK 44 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/help_Nekmo_ffmpeg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | import time 7 | import os 8 | import asyncio 9 | import logging 10 | logging.basicConfig( 11 | level=logging.DEBUG, 12 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 13 | ) 14 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 15 | LOGGER = logging.getLogger(__name__) 16 | 17 | 18 | async def take_screen_shot(video_file, output_directory, ttl): 19 | # https://stackoverflow.com/a/13891070/4723940 20 | out_put_file_name = os.path.join( 21 | output_directory, 22 | str(time.time()) + ".jpg" 23 | ) 24 | if video_file.upper().endswith(("MKV", "MP4", "WEBM")): 25 | file_genertor_command = [ 26 | "ffmpeg", 27 | "-ss", 28 | str(ttl), 29 | "-i", 30 | video_file, 31 | "-vframes", 32 | "1", 33 | out_put_file_name 34 | ] 35 | # width = "90" 36 | process = await asyncio.create_subprocess_exec( 37 | *file_genertor_command, 38 | # stdout must a pipe to be accessible as process.stdout 39 | stdout=asyncio.subprocess.PIPE, 40 | stderr=asyncio.subprocess.PIPE, 41 | ) 42 | # Wait for the subprocess to finish 43 | stdout, stderr = await process.communicate() 44 | stderr.decode().strip() 45 | stdout.decode().strip() 46 | # 47 | if os.path.lexists(out_put_file_name): 48 | return out_put_file_name 49 | else: 50 | return None 51 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/download_from_link.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot import ( 7 | DOWNLOAD_LOCATION 8 | ) 9 | import os 10 | import time 11 | import asyncio 12 | import logging 13 | logging.basicConfig( 14 | level=logging.DEBUG, 15 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 16 | ) 17 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 18 | LOGGER = logging.getLogger(__name__) 19 | 20 | 21 | async def request_download(url, file_name, r_user_id): 22 | directory_path = os.path.join( 23 | DOWNLOAD_LOCATION, str(r_user_id), str( 24 | time.time())) 25 | # create download directory, if not exist 26 | if not os.path.isdir(directory_path): 27 | os.makedirs(directory_path) 28 | local_file_path = os.path.join(directory_path, file_name) 29 | command_to_exec = [ 30 | "wget", 31 | "-O", 32 | local_file_path, 33 | url 34 | ] 35 | process = await asyncio.create_subprocess_exec( 36 | *command_to_exec, 37 | # stdout must a pipe to be accessible as process.stdout 38 | stdout=asyncio.subprocess.PIPE, 39 | stderr=asyncio.subprocess.PIPE, 40 | ) 41 | # Wait for the subprocess to finish 42 | stdout, stderr = await process.communicate() 43 | e_response = stderr.decode().strip() 44 | # logger.info(e_response) 45 | t_response = stdout.decode().strip() 46 | # logger.info(t_response) 47 | final_m_r = e_response + "\n\n\n" + t_response 48 | if os.path.exists(local_file_path): 49 | return True, local_file_path 50 | else: 51 | return False, final_m_r 52 | -------------------------------------------------------------------------------- /tobrot/plugins/call_back_button_handler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot.helper_funcs.youtube_dl_button import youtube_dl_call_back 7 | from tobrot.helper_funcs.download_aria_p_n import aria_start 8 | from tobrot.helper_funcs.admin_check import AdminCheck 9 | from pyrogram import CallbackQuery 10 | import logging 11 | logging.basicConfig( 12 | level=logging.DEBUG, 13 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 14 | LOGGER = logging.getLogger(__name__) 15 | 16 | 17 | async def button(client, update: CallbackQuery): 18 | cb_data = update.data 19 | g = await AdminCheck(client, update.message.chat.id, update.from_user.id) 20 | print(g) 21 | if (update.from_user.id == update.message.reply_to_message.from_user.id) or g: 22 | print(cb_data) 23 | if cb_data.startswith("cancel"): 24 | if len(cb_data) > 1: 25 | i_m_s_e_g = await update.message.reply_text("checking..?", quote=True) 26 | aria_i_p = await aria_start() 27 | g_id = cb_data.split()[-1] 28 | LOGGER.info(g_id) 29 | try: 30 | downloads = aria_i_p.get_download(g_id) 31 | LOGGER.info(downloads) 32 | LOGGER.info(downloads.remove(force=True)) 33 | await i_m_s_e_g.edit_text(f"Leech Cancelled by {update.from_user.first_name}") 34 | except Exception as e: 35 | await i_m_s_e_g.edit_text("FAILED\n\n" + str(e) + "\n#error") 36 | else: 37 | await update.message.delete() 38 | #cb_data = update.data 39 | else: 40 | if "|" in cb_data: 41 | await youtube_dl_call_back(client, update) 42 | -------------------------------------------------------------------------------- /tobrot/sample_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | class Config((object)): 5 | # get a token from @BotFather 6 | TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "") 7 | # The Telegram API things 8 | APP_ID = int(os.environ.get("APP_ID", 12345)) 9 | API_HASH = os.environ.get("API_HASH") 10 | # Get these values from my.telegram.org 11 | # to store the channel ID who are authorized to use the bot 12 | AUTH_CHANNEL = {int(x) for x in os.environ.get("AUTH_CHANNEL", "").split()} 13 | # the download location, where the HTTP Server runs 14 | DOWNLOAD_LOCATION = "./DOWNLOADS" 15 | # Telegram maximum file upload size 16 | MAX_FILE_SIZE = 50000000 17 | TG_MAX_FILE_SIZE = 2097152000 18 | FREE_USER_MAX_FILE_SIZE = 50000000 19 | # chunk size that should be used with requests 20 | CHUNK_SIZE = int(os.environ.get("CHUNK_SIZE", 128)) 21 | # default thumbnail to be used in the videos 22 | DEF_THUMB_NAIL_VID_S = os.environ.get( 23 | "DEF_THUMB_NAIL_VID_S", 24 | "https://placehold.it/90x90") 25 | # maximum message length in Telegram 26 | MAX_MESSAGE_LENGTH = 4096 27 | # set timeout for subprocess 28 | PROCESS_MAX_TIMEOUT = 3600 29 | # 30 | ARIA_TWO_STARTED_PORT = int(os.environ.get("ARIA_TWO_STARTED_PORT", 6800)) 31 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START = int( 32 | os.environ.get("MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START", 600)) 33 | MAX_TG_SPLIT_FILE_SIZE = int( 34 | os.environ.get( 35 | "MAX_TG_SPLIT_FILE_SIZE", 36 | 1072864000)) 37 | # add config vars for the display progress 38 | FINISHED_PROGRESS_STR = os.environ.get("FINISHED_PROGRESS_STR", "█") 39 | UN_FINISHED_PROGRESS_STR = os.environ.get("UN_FINISHED_PROGRESS_STR", "░") 40 | # add offensive API 41 | TG_OFFENSIVE_API = os.environ.get("TG_OFFENSIVE_API", None) 42 | CUSTOM_FILE_NAME = os.environ.get("CUSTOM_FILE_NAME", "") 43 | RCLONE_CONFIG = os.environ.get("RCLONE_CONFIG", "") 44 | DESTINATION_FOLDER = os.environ.get( 45 | "DESTINATION_FOLDER", "TorrentLeech-Gdrive") 46 | INDEX_LINK = os.environ.get("INDEX_LINK", "") 47 | -------------------------------------------------------------------------------- /tobrot/plugins/stats.py: -------------------------------------------------------------------------------- 1 | # © ported from izzy12 by alfiananda84 2 | 3 | import shutil 4 | import psutil 5 | import time 6 | import subprocess 7 | import asyncio 8 | 9 | from tobrot import botStartTime 10 | from tobrot.helper_funcs.helper_stats import get_readable_time, get_readable_file_size 11 | from tobrot import ( 12 | DESTINATION_FOLDER, 13 | RCLONE_CONFIG 14 | ) 15 | 16 | 17 | async def stats_bot_g(client, message): 18 | currentTime = get_readable_time((time.time() - botStartTime)) 19 | total, used, free = shutil.disk_usage('.') 20 | total = get_readable_file_size(total) 21 | used = get_readable_file_size(used) 22 | free = get_readable_file_size(free) 23 | cpuUsage = psutil.cpu_percent(interval=0.5) 24 | memory = psutil.virtual_memory().percent 25 | stats = f'Bot Uptime: {currentTime}\n' \ 26 | f'Total disk space: {total}\n' \ 27 | f'Used: {used}\n' \ 28 | f'Free: {free}\n' \ 29 | f'CPU: {cpuUsage}%\n' \ 30 | f'RAM: {memory}%\n' 31 | await message.reply_text(stats) 32 | 33 | 34 | async def ping_bot_g(client, message): 35 | start_time = int(round(time.time() * 1000)) 36 | i_m_sefg = await message.reply_text(f'ping') 37 | end_time = int(round(time.time() * 1000)) 38 | await i_m_sefg.edit_text(f"""pong! \n{end_time - start_time} ms""") 39 | 40 | 41 | async def check_size_g(client, message): 42 | # await asyncio.sleep(5) 43 | del_it = await message.reply_text("Checking size...") 44 | subprocess.Popen(('touch', 'rclone.conf'), stdout=subprocess.PIPE) 45 | with open('rclone.conf', 'a', newline="\n") as fole: 46 | fole.write("[DRIVE]\n") 47 | fole.write(f"{RCLONE_CONFIG}") 48 | destination = f'{DESTINATION_FOLDER}' 49 | process1 = subprocess.Popen(['rclone', 50 | 'size', 51 | '--config=rclone.conf', 52 | 'DRIVE:' 53 | f'{destination}'], 54 | stdout=subprocess.PIPE, 55 | stderr=subprocess.PIPE) 56 | popi, popp = process1.communicate() 57 | print(popi) 58 | print(popp) 59 | print(popp.decode("utf-8")) 60 | p = popi.decode("utf-8") 61 | print(p) 62 | await asyncio.sleep(5) 63 | await del_it.edit_text(f"Folder {DESTINATION_FOLDER} Info:\n\n{p}") 64 | -------------------------------------------------------------------------------- /tobrot/plugins/custom_thumbnail.py: -------------------------------------------------------------------------------- 1 | """ThumbNail utilities, © @AnyDLBot""" 2 | 3 | 4 | import os 5 | 6 | from tobrot import DOWNLOAD_LOCATION 7 | 8 | from hachoir.metadata import extractMetadata 9 | from hachoir.parser import createParser 10 | from PIL import Image 11 | 12 | 13 | async def save_thumb_nail(client, message): 14 | thumbnail_location = os.path.join( 15 | DOWNLOAD_LOCATION, 16 | "thumbnails" 17 | ) 18 | thumb_image_path = os.path.join( 19 | thumbnail_location, 20 | str(message.from_user.id) + ".jpg" 21 | ) 22 | ismgs = await message.reply_text("processing ...") 23 | if message.reply_to_message is not None: 24 | if not os.path.isdir(thumbnail_location): 25 | os.makedirs(thumbnail_location) 26 | download_location = thumbnail_location + "/" 27 | downloaded_file_name = await client.download_media( 28 | message=message.reply_to_message, 29 | file_name=download_location 30 | ) 31 | # https://stackoverflow.com/a/21669827/4723940 32 | Image.open(downloaded_file_name).convert( 33 | "RGB").save(downloaded_file_name) 34 | metadata = extractMetadata(createParser(downloaded_file_name)) 35 | height = 0 36 | if metadata.has("height"): 37 | height = metadata.get("height") 38 | # resize image 39 | # ref: https://t.me/PyrogramChat/44663 40 | img = Image.open(downloaded_file_name) 41 | # https://stackoverflow.com/a/37631799/4723940 42 | # img.thumbnail((320, 320)) 43 | img.resize((320, height)) 44 | img.save(thumb_image_path, "JPEG") 45 | # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails 46 | os.remove(downloaded_file_name) 47 | await ismgs.edit( 48 | "Custom video / file thumbnail saved. " + 49 | "This image will be used in the upload, till /clearthumbnail." 50 | ) 51 | else: 52 | await message.edit("Reply to a photo to save custom thumbnail") 53 | 54 | 55 | async def clear_thumb_nail(client, message): 56 | thumbnail_location = os.path.join( 57 | DOWNLOAD_LOCATION, 58 | "thumbnails" 59 | ) 60 | thumb_image_path = os.path.join( 61 | thumbnail_location, 62 | str(message.from_user.id) + ".jpg" 63 | ) 64 | ismgs = await message.reply_text("processing ...") 65 | if os.path.exists(thumb_image_path): 66 | os.remove(thumb_image_path) 67 | await ismgs.edit("✅ Custom thumbnail cleared succesfully.") 68 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Telegram Torrent Leecher", 3 | "description": "A Telegram Torrent (and youtube-dl) Leecher based on Pyrogram. Powered by @torrentleechgdrivesupport!", 4 | "keywords": [ 5 | "telegram", 6 | "best", 7 | "indian", 8 | "pyrogram", 9 | "torrent", 10 | "3", 11 | "plugin", 12 | "modular", 13 | "productivity", 14 | "youtube-dl", 15 | "leecher" 16 | ], 17 | "repository": "https://github.com/gautamajay52/TorrentLeech-Gdrive", 18 | "success_url": "https://t.me/torrentleechgdrivesupport", 19 | "website": "https://github.com/gautamajay52/TorrentLeech-Gdrive", 20 | "env": { 21 | "ENV": { 22 | "description": "Setting this to ANYTHING will enable webhooks when in env mode", 23 | "value": "ANYTHING" 24 | }, 25 | "APP_ID": { 26 | "description": "Get this value from https://my.telegram.org", 27 | "value": "" 28 | }, 29 | "API_HASH": { 30 | "description": "Get this value from https://my.telegram.org", 31 | "value": "" 32 | }, 33 | "TG_BOT_TOKEN": { 34 | "description": "get this value from @BotFather", 35 | "value": "" 36 | }, 37 | "AUTH_CHANNEL": { 38 | "description": "should be an integer. The BOT API ID of the Telegram Group, where the Leecher should work.", 39 | "value": "" 40 | }, 41 | "MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START": { 42 | "description": "should be an integer. Number of seconds to wait before cancelling a torrent.", 43 | "required": false 44 | }, 45 | "TG_OFFENSIVE_API": { 46 | "description": "should be an URL accepting the FormParams {i}, {m}, and {t}", 47 | "required": false 48 | }, 49 | "INDEX_LINK": { 50 | "description": "Enter your index link here...dont add '/' at the end of the link", 51 | "value": "" 52 | }, 53 | "RCLONE_CONFIG": { 54 | "description": "Enter your copied text from rclone config. Compulsory for /gleech as well as /tleech command ", 55 | "required": false 56 | }, 57 | "DESTINATION_FOLDER": { 58 | "description": "Enter your Destination folder in which you want to upload yoyr file.", 59 | "required": false 60 | }, 61 | "CUSTOM_FILE_NAME": { 62 | "description": "fill with name u want to prefix the file name like ur channel username🙊, keep empty for do nothing, but add to ur config vars even without input.", 63 | "required": false 64 | } 65 | }, 66 | "addons": [ 67 | ], 68 | "buildpacks": [{ 69 | "url": "https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest" 70 | }, { 71 | "url": "https://github.com/SayanthD/aria2-heroku" 72 | }, { 73 | "url": "https://github.com/amivin/rclone-heroku" 74 | }, { 75 | "url": "https://github.com/HasibulKabir/heroku-buildpack-rarlab" 76 | }, { 77 | "url": "heroku/python" 78 | }], 79 | "formation": { 80 | "worker": { 81 | "quantity": 1, 82 | "size": "free" 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/download.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) gautamajay52 | Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot.helper_funcs.create_compressed_archive import unzip_me, unrar_me, untar_me 7 | from tobrot.helper_funcs.upload_to_tg import upload_to_gdrive 8 | from tobrot.helper_funcs.display_progress_g import progress_for_pyrogram_g 9 | from tobrot import ( 10 | DOWNLOAD_LOCATION 11 | ) 12 | from datetime import datetime 13 | import subprocess 14 | import time 15 | import os 16 | import asyncio 17 | import logging 18 | logging.basicConfig( 19 | level=logging.DEBUG, 20 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 21 | ) 22 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 23 | LOGGER = logging.getLogger(__name__) 24 | # 25 | 26 | 27 | async def down_load_media_f(client, message): 28 | mess_age = await message.reply_text("...", quote=True) 29 | if not os.path.isdir(DOWNLOAD_LOCATION): 30 | os.makedirs(DOWNLOAD_LOCATION) 31 | if message.reply_to_message is not None: 32 | start_t = datetime.now() 33 | download_location = DOWNLOAD_LOCATION + "/" 34 | c_time = time.time() 35 | the_real_download_location = await client.download_media( 36 | message=message.reply_to_message, 37 | file_name=download_location, 38 | progress=progress_for_pyrogram_g, 39 | progress_args=( 40 | "trying to download", mess_age, c_time 41 | ) 42 | ) 43 | end_t = datetime.now() 44 | ms = (end_t - start_t).seconds 45 | print(the_real_download_location) 46 | await mess_age.edit_text(f"Downloaded to {the_real_download_location} in {ms} seconds") 47 | gk = subprocess.Popen( 48 | ['mv', f'{the_real_download_location}', '/app/'], stdout=subprocess.PIPE) 49 | gk.communicate() 50 | the_real_download_location_g = os.path.basename( 51 | the_real_download_location) 52 | if len(message.command) > 1: 53 | if message.command[1] == "unzip": 54 | file_upload = await unzip_me(the_real_download_location_g) 55 | if file_upload is not None: 56 | g_response = await upload_to_gdrive(file_upload, mess_age) 57 | LOGGER.info(g_response) 58 | 59 | elif message.command[1] == "unrar": 60 | file_uploade = await unrar_me(the_real_download_location_g) 61 | if file_uploade is not None: 62 | gk_response = await upload_to_gdrive(file_uploade, mess_age) 63 | LOGGER.info(gk_response) 64 | 65 | elif message.command[1] == "untar": 66 | file_uploadg = await untar_me(the_real_download_location_g) 67 | if file_uploadg is not None: 68 | gau_response = await upload_to_gdrive(file_uploadg, mess_age) 69 | LOGGER.info(gau_response) 70 | else: 71 | gaut_response = await upload_to_gdrive(the_real_download_location_g, mess_age) 72 | LOGGER.info(gaut_response) 73 | else: 74 | await asyncio.sleep(10) 75 | await mess_age.edit_text("Reply to a Telegram Media, to upload to the Cloud Drive.") 76 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/display_progress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot import ( 7 | FINISHED_PROGRESS_STR, 8 | UN_FINISHED_PROGRESS_STR 9 | ) 10 | import time 11 | import math 12 | import logging 13 | logging.basicConfig( 14 | level=logging.DEBUG, 15 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | async def progress_for_pyrogram( 20 | current, 21 | total, 22 | ud_type, 23 | message, 24 | start 25 | ): 26 | now = time.time() 27 | diff = now - start 28 | if round(diff % 10.00) == 0 or current == total: 29 | # if round(current / total * 100, 0) % 5 == 0: 30 | percentage = current * 100 / total 31 | speed = current / diff 32 | elapsed_time = round(diff) * 1000 33 | time_to_completion = round((total - current) / speed) * 1000 34 | estimated_total_time = elapsed_time + time_to_completion 35 | 36 | elapsed_time = TimeFormatter(milliseconds=elapsed_time) 37 | estimated_total_time = TimeFormatter(milliseconds=estimated_total_time) 38 | 39 | progress = "[{0}{1}] \nP: {2}%\n".format( 40 | ''.join([FINISHED_PROGRESS_STR for i in range(math.floor(percentage / 5))]), 41 | ''.join([UN_FINISHED_PROGRESS_STR for i in range(20 - math.floor(percentage / 5))]), 42 | round(percentage, 2)) 43 | 44 | tmp = progress + "{0} of {1}\nSpeed: {2}/s\nETA: {3}\n".format( 45 | humanbytes(current), 46 | humanbytes(total), 47 | humanbytes(speed), 48 | # elapsed_time if elapsed_time != '' else "0 s", 49 | estimated_total_time if estimated_total_time != '' else "0 s" 50 | ) 51 | try: 52 | if not message.photo: 53 | await message.edit_text( 54 | text="{}\n {}".format( 55 | ud_type, 56 | tmp 57 | ) 58 | ) 59 | else: 60 | await message.edit_caption( 61 | caption="{}\n {}".format( 62 | ud_type, 63 | tmp 64 | ) 65 | ) 66 | except BaseException: 67 | pass 68 | 69 | 70 | def humanbytes(size): 71 | # https://stackoverflow.com/a/49361727/4723940 72 | # 2**10 = 1024 73 | if not size: 74 | return "" 75 | power = 2**10 76 | n = 0 77 | Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'} 78 | while size > power: 79 | size /= power 80 | n += 1 81 | return str(round(size, 2)) + " " + Dic_powerN[n] + 'B' 82 | 83 | 84 | def TimeFormatter(milliseconds: int) -> str: 85 | seconds, milliseconds = divmod(int(milliseconds), 1000) 86 | minutes, seconds = divmod(seconds, 60) 87 | hours, minutes = divmod(minutes, 60) 88 | days, hours = divmod(hours, 24) 89 | tmp = ((str(days) + "d, ") if days else "") + \ 90 | ((str(hours) + "h, ") if hours else "") + \ 91 | ((str(minutes) + "m, ") if minutes else "") + \ 92 | ((str(seconds) + "s, ") if seconds else "") + \ 93 | ((str(milliseconds) + "ms, ") if milliseconds else "") 94 | return tmp[:-2] 95 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/display_progress_g.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot import ( 7 | FINISHED_PROGRESS_STR, 8 | UN_FINISHED_PROGRESS_STR, 9 | ) 10 | import time 11 | import math 12 | import logging 13 | logging.basicConfig( 14 | level=logging.DEBUG, 15 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 16 | logger = logging.getLogger(__name__) 17 | 18 | 19 | async def progress_for_pyrogram_g( 20 | current, 21 | total, 22 | ud_type, 23 | message, 24 | start 25 | ): 26 | """ generic progress display for Telegram Upload / Download status """ 27 | now = time.time() 28 | diff = now - start 29 | if round(diff % 10.00) == 0 or current == total: 30 | # if round(current / total * 100, 0) % 5 == 0: 31 | percentage = current * 100 / total 32 | speed = current / diff 33 | elapsed_time = round(diff) * 1000 34 | time_to_completion = round((total - current) / speed) * 1000 35 | estimated_total_time = elapsed_time + time_to_completion 36 | 37 | elapsed_time = time_formatter(milliseconds=elapsed_time) 38 | estimated_total_time = time_formatter( 39 | milliseconds=estimated_total_time) 40 | 41 | progress = "[{0}{1}] \nP: {2}%\n".format( 42 | ''.join([FINISHED_PROGRESS_STR for i in range(math.floor(percentage / 5))]), 43 | ''.join([UN_FINISHED_PROGRESS_STR for i in range(20 - math.floor(percentage / 5))]), 44 | round(percentage, 2)) 45 | 46 | tmp = progress + "{0} of {1}\nSpeed: {2}/s\nETA: {3}\n".format( 47 | humanbytes(current), 48 | humanbytes(total), 49 | humanbytes(speed), 50 | # elapsed_time if elapsed_time != '' else "0 s", 51 | estimated_total_time if estimated_total_time != '' else "0 s" 52 | ) 53 | try: 54 | await message.edit( 55 | "{}\n {}".format( 56 | ud_type, 57 | tmp 58 | ) 59 | ) 60 | except BaseException: 61 | pass 62 | 63 | 64 | def humanbytes(size: int) -> str: 65 | """ converts bytes into human readable format """ 66 | # https://stackoverflow.com/a/49361727/4723940 67 | # 2**10 = 1024 68 | if not size: 69 | return "" 70 | power = 2 ** 10 71 | number = 0 72 | dict_power_n = { 73 | 0: " ", 74 | 1: "Ki", 75 | 2: "Mi", 76 | 3: "Gi", 77 | 4: "Ti" 78 | } 79 | while size > power: 80 | size /= power 81 | number += 1 82 | return str(round(size, 2)) + " " + dict_power_n[number] + 'B' 83 | 84 | 85 | def time_formatter(milliseconds: int) -> str: 86 | """ converts seconds into human readable format """ 87 | seconds, milliseconds = divmod(int(milliseconds), 1000) 88 | minutes, seconds = divmod(seconds, 60) 89 | hours, minutes = divmod(minutes, 60) 90 | days, hours = divmod(hours, 24) 91 | tmp = ((str(days) + "d, ") if days else "") + \ 92 | ((str(hours) + "h, ") if hours else "") + \ 93 | ((str(minutes) + "m, ") if minutes else "") + \ 94 | ((str(seconds) + "s, ") if seconds else "") + \ 95 | ((str(milliseconds) + "ms, ") if milliseconds else "") 96 | return tmp[:-2] 97 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/extract_link_from_message.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot import ( 7 | TG_OFFENSIVE_API 8 | ) 9 | from pyrogram import MessageEntity 10 | import aiohttp 11 | import logging 12 | logging.basicConfig( 13 | level=logging.DEBUG, 14 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 15 | ) 16 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 17 | LOGGER = logging.getLogger(__name__) 18 | 19 | 20 | def extract_url_from_entity(entities: MessageEntity, text: str): 21 | url = None 22 | for entity in entities: 23 | if entity.type == "text_link": 24 | url = entity.url 25 | elif entity.type == "url": 26 | o = entity.offset 27 | l = entity.length 28 | url = text[o:o + l] 29 | return url 30 | 31 | 32 | async def extract_link(message, type_o_request): 33 | custom_file_name = None 34 | url = None 35 | youtube_dl_username = None 36 | youtube_dl_password = None 37 | 38 | if message is None: 39 | url = None 40 | custom_file_name = None 41 | 42 | elif message.text is not None: 43 | if message.text.lower().startswith("magnet:"): 44 | url = message.text.strip() 45 | 46 | elif "|" in message.text: 47 | url_parts = message.text.split("|") 48 | if len(url_parts) == 2: 49 | url = url_parts[0] 50 | custom_file_name = url_parts[1] 51 | elif len(url_parts) == 4: 52 | url = url_parts[0] 53 | custom_file_name = url_parts[1] 54 | youtube_dl_username = url_parts[2] 55 | youtube_dl_password = url_parts[3] 56 | 57 | elif message.entities is not None: 58 | url = extract_url_from_entity(message.entities, message.text) 59 | 60 | else: 61 | url = message.text.strip() 62 | 63 | elif message.document is not None: 64 | if message.document.file_name.lower().endswith(".torrent"): 65 | url = await message.download() 66 | custom_file_name = message.caption 67 | 68 | elif message.caption is not None: 69 | if "|" in message.caption: 70 | url_parts = message.caption.split("|") 71 | if len(url_parts) == 2: 72 | url = url_parts[0] 73 | custom_file_name = url_parts[1] 74 | elif len(url_parts) == 4: 75 | url = url_parts[0] 76 | custom_file_name = url_parts[1] 77 | youtube_dl_username = url_parts[2] 78 | youtube_dl_password = url_parts[3] 79 | 80 | elif message.caption_entities is not None: 81 | url = extract_url_from_entity( 82 | message.caption_entities, message.caption) 83 | 84 | else: 85 | url = message.caption.strip() 86 | 87 | elif message.entities is not None: 88 | url = message.text 89 | 90 | # trim blank spaces from the URL 91 | # might have some issues with #45 92 | if url is not None: 93 | url = url.strip() 94 | if custom_file_name is not None: 95 | custom_file_name = custom_file_name.strip() 96 | # https://stackoverflow.com/a/761825/4723940 97 | if youtube_dl_username is not None: 98 | youtube_dl_username = youtube_dl_username.strip() 99 | if youtube_dl_password is not None: 100 | youtube_dl_password = youtube_dl_password.strip() 101 | 102 | # additional conditional check, 103 | # here to FILTER out BAD URLs 104 | LOGGER.info(TG_OFFENSIVE_API) 105 | if TG_OFFENSIVE_API is not None: 106 | try: 107 | async with aiohttp.ClientSession() as session: 108 | api_url = TG_OFFENSIVE_API.format( 109 | i=url, 110 | m=custom_file_name, 111 | t=type_o_request 112 | ) 113 | LOGGER.info(api_url) 114 | async with session.get(api_url) as resp: 115 | suats = int(resp.status) 116 | err = await resp.text() 117 | if suats != 200: 118 | url = None 119 | custom_file_name = err 120 | except BaseException: 121 | # this might occur in case of a BAD API URL, 122 | # who knows? :\ 123 | pass 124 | 125 | return url, custom_file_name, youtube_dl_username, youtube_dl_password 126 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/split_large_files.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot import ( 7 | MAX_TG_SPLIT_FILE_SIZE 8 | ) 9 | from hachoir.parser import createParser 10 | from hachoir.metadata import extractMetadata 11 | import time 12 | import os 13 | import asyncio 14 | import logging 15 | logging.basicConfig( 16 | level=logging.DEBUG, 17 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 18 | ) 19 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 20 | LOGGER = logging.getLogger(__name__) 21 | 22 | 23 | async def split_large_files(input_file): 24 | working_directory = os.path.dirname(os.path.abspath(input_file)) 25 | new_working_directory = os.path.join( 26 | working_directory, 27 | str(time.time()) 28 | ) 29 | # create download directory, if not exist 30 | if not os.path.isdir(new_working_directory): 31 | os.makedirs(new_working_directory) 32 | # if input_file.upper().endswith(("MKV", "MP4", "WEBM", "MP3", "M4A", 33 | # "FLAC", "WAV")): 34 | """The below logic is DERPed, so removing temporarily 35 | """ 36 | if False: 37 | # handle video / audio files here 38 | metadata = extractMetadata(createParser(input_file)) 39 | total_duration = 0 40 | if metadata.has("duration"): 41 | total_duration = metadata.get('duration').seconds 42 | # proprietary logic to get the seconds to trim (at) 43 | LOGGER.info(total_duration) 44 | total_file_size = os.path.getsize(input_file) 45 | LOGGER.info(total_file_size) 46 | minimum_duration = ( 47 | total_duration / total_file_size) * (MAX_TG_SPLIT_FILE_SIZE) 48 | LOGGER.info(minimum_duration) 49 | # END: proprietary 50 | start_time = 0 51 | end_time = minimum_duration 52 | base_name = os.path.basename(input_file) 53 | input_extension = base_name.split(".")[-1] 54 | LOGGER.info(input_extension) 55 | i = 0 56 | while end_time < total_duration: 57 | LOGGER.info(i) 58 | parted_file_name = "" 59 | parted_file_name += str(i).zfill(5) 60 | parted_file_name += str(base_name) 61 | parted_file_name += "_PART_" 62 | parted_file_name += str(start_time) 63 | parted_file_name += "." 64 | parted_file_name += str(input_extension) 65 | output_file = os.path.join(new_working_directory, parted_file_name) 66 | LOGGER.info(output_file) 67 | LOGGER.info(await cult_small_video( 68 | input_file, 69 | output_file, 70 | str(start_time), 71 | str(end_time) 72 | )) 73 | start_time = end_time 74 | end_time = end_time + minimum_duration 75 | i = i + 1 76 | else: 77 | # handle normal files here 78 | o_d_t = os.path.join( 79 | new_working_directory, 80 | os.path.basename(input_file) 81 | ) 82 | o_d_t = o_d_t + "." 83 | file_genertor_command = [ 84 | "split", 85 | "--numeric-suffixes=1", 86 | "--suffix-length=5", 87 | f"--bytes={MAX_TG_SPLIT_FILE_SIZE}", 88 | input_file, 89 | o_d_t 90 | ] 91 | process = await asyncio.create_subprocess_exec( 92 | *file_genertor_command, 93 | # stdout must a pipe to be accessible as process.stdout 94 | stdout=asyncio.subprocess.PIPE, 95 | stderr=asyncio.subprocess.PIPE, 96 | ) 97 | # Wait for the subprocess to finish 98 | stdout, stderr = await process.communicate() 99 | stderr.decode().strip() 100 | stdout.decode().strip() 101 | return new_working_directory 102 | 103 | 104 | async def cult_small_video(video_file, out_put_file_name, start_time, end_time): 105 | file_genertor_command = [ 106 | "ffmpeg", 107 | "-hide_banner", 108 | "-i", 109 | video_file, 110 | "-ss", 111 | start_time, 112 | "-to", 113 | end_time, 114 | "-async", 115 | "1", 116 | "-strict", 117 | "-2", 118 | "-c", 119 | "copy", 120 | out_put_file_name 121 | ] 122 | process = await asyncio.create_subprocess_exec( 123 | *file_genertor_command, 124 | # stdout must a pipe to be accessible as process.stdout 125 | stdout=asyncio.subprocess.PIPE, 126 | stderr=asyncio.subprocess.PIPE, 127 | ) 128 | # Wait for the subprocess to finish 129 | stdout, stderr = await process.communicate() 130 | stderr.decode().strip() 131 | t_response = stdout.decode().strip() 132 | LOGGER.info(t_response) 133 | return out_put_file_name 134 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/create_compressed_archive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | # the logging things 6 | import subprocess 7 | import shutil 8 | import os 9 | import asyncio 10 | import logging 11 | logging.basicConfig( 12 | level=logging.DEBUG, 13 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' 14 | ) 15 | LOGGER = logging.getLogger(__name__) 16 | 17 | 18 | async def create_archive(input_directory): 19 | return_name = None 20 | if os.path.exists(input_directory): 21 | base_dir_name = os.path.basename(input_directory) 22 | compressed_file_name = f"{base_dir_name}.tar.gz" 23 | # #BlameTelegram 24 | suffix_extention_length = 1 + 3 + 1 + 2 25 | if len(base_dir_name) > (64 - suffix_extention_length): 26 | compressed_file_name = base_dir_name[0:( 27 | 64 - suffix_extention_length)] 28 | compressed_file_name += ".tar.gz" 29 | # fix for https://t.me/c/1434259219/13344 30 | file_genertor_command = [ 31 | "tar", 32 | "-zcvf", 33 | compressed_file_name, 34 | f"{input_directory}" 35 | ] 36 | process = await asyncio.create_subprocess_exec( 37 | *file_genertor_command, 38 | # stdout must a pipe to be accessible as process.stdout 39 | stdout=asyncio.subprocess.PIPE, 40 | stderr=asyncio.subprocess.PIPE, 41 | ) 42 | # Wait for the subprocess to finish 43 | stdout, stderr = await process.communicate() 44 | stderr.decode().strip() 45 | stdout.decode().strip() 46 | if os.path.exists(compressed_file_name): 47 | try: 48 | shutil.rmtree(input_directory) 49 | except BaseException: 50 | pass 51 | return_name = compressed_file_name 52 | return return_name 53 | 54 | # 55 | 56 | 57 | async def unzip_me(input_directory): 58 | return_name = None 59 | if os.path.exists(input_directory): 60 | base_dir_name = os.path.basename(input_directory) 61 | uncompressed_file_name = os.path.splitext(base_dir_name)[0] 62 | # #BlameTelegram 63 | #suffix_extention_length = 1 + 3 + 1 + 2 64 | # if len(base_dir_name) > (64 - suffix_extention_length): 65 | #compressed_file_name = base_dir_name[0:(64 - suffix_extention_length)] 66 | #compressed_file_name += ".tar.gz" 67 | # fix for https://t.me/c/1434259219/13344 68 | process = subprocess.Popen([ 69 | "unzip", 70 | "-o", 71 | f"{base_dir_name}", 72 | "-d", 73 | f"{uncompressed_file_name}"], 74 | stdout=subprocess.PIPE 75 | ) 76 | # Wait for the subprocess to finish 77 | stdout, stderr = process.communicate() 78 | print(stdout) 79 | print(stderr) 80 | #e_response = stderr.decode().strip() 81 | #t_response = stdout.decode().strip() 82 | if os.path.exists(uncompressed_file_name): 83 | try: 84 | os.remove(input_directory) 85 | except BaseException: 86 | pass 87 | return_name = uncompressed_file_name 88 | print(return_name) 89 | return return_name 90 | # 91 | 92 | 93 | async def untar_me(input_directory): 94 | return_name = None 95 | if os.path.exists(input_directory): 96 | print(input_directory) 97 | base_dir_name = os.path.basename(input_directory) 98 | uncompressed_file_name = os.path.splitext(base_dir_name)[0] 99 | subprocess.Popen( 100 | ('mkdir', 101 | f'{uncompressed_file_name}'), 102 | stdout=subprocess.PIPE, 103 | stderr=subprocess.PIPE) 104 | process = subprocess.Popen([ 105 | "tar", 106 | "-xvf", 107 | f"{base_dir_name}", 108 | "-C" 109 | f"{uncompressed_file_name}"], 110 | stdout=subprocess.PIPE, 111 | stderr=subprocess.PIPE 112 | ) 113 | # Wait for the subprocess to finish 114 | stdout, stderr = process.communicate() 115 | print(stdout) 116 | print(stderr) 117 | #e_response = stderr.decode().strip() 118 | #t_response = stdout.decode().strip() 119 | if os.path.exists(uncompressed_file_name): 120 | try: 121 | os.remove(input_directory) 122 | except BaseException: 123 | pass 124 | return_name = uncompressed_file_name 125 | print(return_name) 126 | return return_name 127 | # 128 | 129 | 130 | async def unrar_me(input_directory): 131 | return_name = None 132 | if os.path.exists(input_directory): 133 | base_dir_name = os.path.basename(input_directory) 134 | uncompressed_file_name = os.path.splitext(base_dir_name)[0] 135 | subprocess.Popen( 136 | ('mkdir', 137 | f'{uncompressed_file_name}'), 138 | stdout=subprocess.PIPE) 139 | print(base_dir_name) 140 | process = subprocess.Popen([ 141 | "unrar", 142 | "x", 143 | f"{base_dir_name}", 144 | f"{uncompressed_file_name}"], 145 | stdout=subprocess.PIPE 146 | ) 147 | # Wait for the subprocess to finish 148 | stdout, stderr = process.communicate() 149 | print(stdout) 150 | print(stderr) 151 | #e_response = stderr.decode().strip() 152 | #t_response = stdout.decode().strip() 153 | if os.path.exists(uncompressed_file_name): 154 | try: 155 | os.remove(input_directory) 156 | except BaseException: 157 | pass 158 | return_name = uncompressed_file_name 159 | print(return_name) 160 | return return_name 161 | -------------------------------------------------------------------------------- /tobrot/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | # the logging things 6 | from tobrot.helper_funcs.download import down_load_media_f 7 | from tobrot.plugins.custom_thumbnail import ( 8 | save_thumb_nail, 9 | clear_thumb_nail 10 | ) 11 | from tobrot.plugins.call_back_button_handler import button 12 | from tobrot.plugins.status_message_fn import ( 13 | status_message_f, 14 | cancel_message_f, 15 | exec_message_f, 16 | upload_document_f 17 | # eval_message_f 18 | ) 19 | from tobrot.plugins.incoming_message_fn import incoming_message_f, incoming_youtube_dl_f, incoming_purge_message_f, incoming_gdrive_message_f 20 | from tobrot.plugins.help_bot import help_bot_message 21 | from tobrot.plugins.stats import check_size_g 22 | from tobrot.plugins.stats import ping_bot_g 23 | from tobrot.plugins.stats import stats_bot_g 24 | from tobrot.plugins.new_join_fn import new_join_f, help_message_f, rename_message_f 25 | from pyrogram import Client, Filters, MessageHandler, CallbackQueryHandler 26 | from tobrot import ( 27 | DOWNLOAD_LOCATION, 28 | TG_BOT_TOKEN, 29 | APP_ID, 30 | API_HASH, 31 | AUTH_CHANNEL, 32 | ) 33 | import os 34 | import logging 35 | logging.basicConfig( 36 | level=logging.DEBUG, 37 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 38 | ) 39 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 40 | logging.getLogger("urllib3").setLevel(logging.WARNING) 41 | LOGGER = logging.getLogger(__name__) 42 | 43 | 44 | if __name__ == "__main__": 45 | # create download directory, if not exist 46 | if not os.path.isdir(DOWNLOAD_LOCATION): 47 | os.makedirs(DOWNLOAD_LOCATION) 48 | # 49 | app = Client( 50 | "LeechBot", 51 | bot_token=TG_BOT_TOKEN, 52 | api_id=APP_ID, 53 | api_hash=API_HASH, 54 | workers=343 55 | ) 56 | # 57 | incoming_message_handler = MessageHandler( 58 | incoming_message_f, filters=Filters.command( 59 | [f"mirrorup"]) & Filters.chat( 60 | chats=AUTH_CHANNEL)) 61 | app.add_handler(incoming_message_handler) 62 | # 63 | incoming_gdrive_message_handler = MessageHandler( 64 | incoming_gdrive_message_f, 65 | filters=Filters.command([f"mirror"]) & Filters.chat(chats=AUTH_CHANNEL) 66 | ) 67 | app.add_handler(incoming_gdrive_message_handler) 68 | # 69 | incoming_telegram_download_handler = MessageHandler( 70 | down_load_media_f, filters=Filters.command( 71 | [f"tmirror"]) & Filters.chat( 72 | chats=AUTH_CHANNEL)) 73 | app.add_handler(incoming_telegram_download_handler) 74 | # 75 | incoming_purge_message_handler = MessageHandler( 76 | incoming_purge_message_f, 77 | filters=Filters.command(["purge"]) & Filters.chat(chats=AUTH_CHANNEL) 78 | ) 79 | app.add_handler(incoming_purge_message_handler) 80 | # 81 | incoming_youtube_dl_handler = MessageHandler( 82 | incoming_youtube_dl_f, 83 | filters=Filters.command([f"ytdl"]) & Filters.chat(chats=AUTH_CHANNEL) 84 | ) 85 | app.add_handler(incoming_youtube_dl_handler) 86 | # 87 | incoming_size_checker_handler = MessageHandler( 88 | check_size_g, 89 | filters=Filters.command(["getsize"]) & Filters.chat(chats=AUTH_CHANNEL) 90 | ) 91 | app.add_handler(incoming_size_checker_handler) 92 | # 93 | incoming_bot_stats_handler = MessageHandler( 94 | stats_bot_g, 95 | filters=Filters.command(["stats"]) & Filters.chat(chats=AUTH_CHANNEL) 96 | ) 97 | app.add_handler(incoming_bot_stats_handler) 98 | # 99 | ping_message_handler = MessageHandler( 100 | ping_bot_g, 101 | filters=Filters.command(["ping"]) & Filters.chat(chats=AUTH_CHANNEL) 102 | ) 103 | app.add_handler(ping_message_handler) 104 | # 105 | status_message_handler = MessageHandler( 106 | status_message_f, 107 | filters=Filters.command(["status"]) & Filters.chat(chats=AUTH_CHANNEL) 108 | ) 109 | app.add_handler(status_message_handler) 110 | # 111 | cancel_message_handler = MessageHandler( 112 | cancel_message_f, 113 | filters=Filters.command(["cancel"]) & Filters.chat(chats=AUTH_CHANNEL) 114 | ) 115 | app.add_handler(cancel_message_handler) 116 | # 117 | exec_message_handler = MessageHandler( 118 | exec_message_f, 119 | filters=Filters.command(["exec"]) & Filters.chat(chats=AUTH_CHANNEL) 120 | ) 121 | app.add_handler(exec_message_handler) 122 | # 123 | ''' 124 | eval_message_handler = MessageHandler( 125 | eval_message_f, 126 | filters=Filters.command(["eval"]) & Filters.chat(chats=AUTH_CHANNEL) 127 | ) 128 | app.add_handler(eval_message_handler) 129 | ''' 130 | # 131 | rename_message_handler = MessageHandler( 132 | rename_message_f, 133 | filters=Filters.command(["index"]) & Filters.chat(chats=AUTH_CHANNEL) 134 | ) 135 | app.add_handler(rename_message_handler) 136 | # 137 | upload_document_handler = MessageHandler( 138 | upload_document_f, 139 | filters=Filters.command(["upload"]) & Filters.chat(chats=AUTH_CHANNEL) 140 | ) 141 | app.add_handler(upload_document_handler) 142 | # 143 | help_text_handler = MessageHandler( 144 | help_message_f, 145 | filters=Filters.command(["start"]) & Filters.chat(chats=AUTH_CHANNEL) 146 | ) 147 | app.add_handler(help_text_handler) 148 | # 149 | help_bot_text_handler = MessageHandler( 150 | help_bot_message, 151 | filters=Filters.command(["help"]) & Filters.chat(chats=AUTH_CHANNEL) 152 | ) 153 | app.add_handler(help_bot_text_handler) 154 | # 155 | new_join_handler = MessageHandler( 156 | new_join_f, 157 | filters=~Filters.chat(chats=AUTH_CHANNEL) 158 | ) 159 | app.add_handler(new_join_handler) 160 | # 161 | call_back_button_handler = CallbackQueryHandler( 162 | button 163 | ) 164 | app.add_handler(call_back_button_handler) 165 | # 166 | save_thumb_nail_handler = MessageHandler( 167 | save_thumb_nail, filters=Filters.command( 168 | ["savethumbnail"]) & Filters.chat( 169 | chats=AUTH_CHANNEL)) 170 | app.add_handler(save_thumb_nail_handler) 171 | # 172 | clear_thumb_nail_handler = MessageHandler( 173 | clear_thumb_nail, filters=Filters.command( 174 | ["clearthumbnail"]) & Filters.chat( 175 | chats=AUTH_CHANNEL)) 176 | app.add_handler(clear_thumb_nail_handler) 177 | # 178 | app.run() 179 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # for support join here [TorrentLeech-Gdrive](https://telegram.dog/torrentleechgdrivesupport) 2 | # working example group [Leech Here](https://telegram.dog/torrentleechgdrive) 3 | 4 | # Original Repo 5 | https://github.com/gautamajay52/TorrentLeech-Gdrive 6 | 7 | # Telegram Torrent Leecher 🔥🤖 8 | 9 | A Telegram Torrent (and youtube-dl) Leecher based on [Pyrogram](https://github.com/pyrogram/pyrogram) 10 | 11 | # Benefits :- 12 | ✓ Telegram File mirrorring to cloud along with its unzipping, unrar and untar 13 | ✓ Drive/Teamdrive support/All other cloud services rclone.org supports 14 | ✓ Unzip 15 | ✓ Unrar 16 | ✓ Untar 17 | ✓ Custom file name 18 | ✓ Custom commands 19 | ✓ 20 | 21 | ### Credit goes to SpEcHiDe for his Publicleech repo. 22 | 23 | ## installing 24 | 25 | ### The Easy Way 26 | 27 | [![Deploy](https://www.herokucdn.com/deploy/button.svg)](https://heroku.com/deploy) 28 | 29 | ### The Legacy Way 30 | Simply clone the repository and run the main file: 31 | 32 | ```sh 33 | git clone https://github.com/SpEcHiDe/PublicLeech.git 34 | cd PublicLeech 35 | virtualenv -p /usr/bin/python3 venv 36 | . ./venv/bin/activate 37 | pip install -r requirements.txt 38 | # 39 | python3 -m tobrot 40 | ``` 41 | 42 | ### an example config.py 👇 43 | ```py 44 | from tobrot.sample_config import Config 45 | 46 | class Config(Config): 47 | TG_BOT_TOKEN = "" 48 | APP_ID = 6 49 | API_HASH = "eb06d4abfb49dc3eeb1aeb98ae0f581e" 50 | AUTH_CHANNEL = -1001234567890 51 | ``` 52 | 53 | ### Variable Explanations 54 | 55 | ##### Mandatory Variables 56 | 57 | * `TG_BOT_TOKEN`: Create a bot using [@BotFather](https://telegram.dog/BotFather), and get the Telegram API token. 58 | 59 | * `APP_ID` 60 | * `API_HASH`: Get these two values from [my.telegram.org/apps](https://my.telegram.org/apps). 61 | * N.B.: if Telegram is blocked by your ISP, try our [Telegram bot](https://telegram.dog/UseTGXBot) to get the IDs. 62 | 63 | * `AUTH_CHANNEL`: Create a Super Group in Telegram, add `@GoogleIMGBot` to the group, and send /id in the chat, to get this value. 64 | 65 | * `RCLONE_CONFIG`: Create the rclone config using the rclone.org and read the rclone section for the next. 66 | 67 | * `DESTINATION_FOLDER`: Name of your folder in ur respective drive where you want to upload the files using the bot. 68 | 69 | ##### Set Rclone 70 | 71 | 1. Set Rclone locally by following the official repo : https://rclone.org/docs/ 72 | 2. Get your `rclone.conf` file. 73 | will look like this 74 | ``` 75 | [NAME] 76 | type = 77 | scope = 78 | token = 79 | client_id = 80 | client_secret = 81 | 82 | ``` 83 | 3. Only copy the config of drive u want to upload file. 84 | 4. Copy the entries of `rclone.conf` 85 | 5. Your copied config should look like this: 86 | ``` 87 | type = 88 | scope = 89 | token = 90 | client_id = 91 | client_secret = 92 | 93 | and everythin except `[NAME]` 94 | 95 | ``` 96 | 97 | 6. Paste copied config in `RCLONE_CONFIG` 98 | 99 | 7. Hit deploy button. 100 | 8. Examples:- 101 |

102 | 103 | 104 | 105 |

106 | 107 | ## FAQ 108 | 109 | ##### Optional Configuration Variables 110 | 111 | * `MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START` 112 | 113 | * `TG_OFFENSIVE_API` 114 | 115 | * `CUSTOM_FILE_NAME` 116 | 117 | * `INDEX_LINK`: (Without `/` at last of the link, otherwise u will get error) During creating index, plz fill `Default Root ID` with the id of your `DESTINATION_FOLDER` after creating. Otherwise index will not work properly. 118 | ## Available Commands 119 | 120 | * `/ytdl`: This command should be used as reply to a [supported link](https://ytdl-org.github.io/youtube-dl/supportedsites.html) and upload to telegram 121 | 122 | * `/ytdl gdrive`: This command should be used as reply to a [supported link](https://ytdl-org.github.io/youtube-dl/supportedsites.html) and upload to gdrive 123 | 124 | * `/mirror`: This command should be used as reply to a magnetic link, a torrent link, or a direct link. And this will download the files from the given link or torrent and will upload to the drive using rclone. 125 | 126 | * `/mirror archive`: This command should be used as reply to a magnetic link, a torrent link, or a direct link. [This command will create a .tar.gz file of the output directory, and send the files in the chat, splited into PARTS of 1024MiB each, due to Telegram limitations] 127 | 128 | * `/mirror unzip`: This will unzip the .zip file and upload to drive. 129 | 130 | * `/mirror untar`: This will untar the .tar file and upload to drive. 131 | 132 | * `/mirror unrar`: This will unrar the .rar file and upload to drive. 133 | 134 | * `/mirrorup`: This command should be used as reply to a magnetic link, a torrent link, or a direct link. [this command will SPAM the chat and send the downloads a seperate files, if there is more than one file, in the specified torrent] 135 | 136 | * `/mirrorup unzip`: This will unzip the .zip file and upload to telegram. 137 | 138 | * `/mirrorup untar`: This will untar the .tar file and upload to telegram. 139 | 140 | * `/mirrorup unrar`: This will unrar the .rar file and upload to telegram. 141 | 142 | * `/tmirror`: This will mirror the telegram files to ur respective drive. 143 | 144 | * `/tmirror unzip`: This will unzip the .zip telegram file and upload to drive. 145 | 146 | * `/tmirror unrar`: This will unrar the .rar telegram file and upload to drive. 147 | 148 | * `/tmirror untar`: This will untar the .tar telegram file and upload to drive. 149 | 150 | 151 | * [Only work with direct link for now]It is like u can add custom name as prefix of the original file name. 152 | Like if your file name is `gk.txt` uploaded will be what u add in `CUSTOM_FILE_NAME` + `gk.txt` 153 | 154 | Only works with direct link.No magnet or torrent. 155 | 156 | And also added custom name like... 157 | 158 | You have to pass link as 159 | `www.download.me/gk.txt | new.txt` 160 | 161 | the file will be uploaded as `new.txt`. 162 | 163 | 164 | ## How to Use? 165 | 166 | * send any one of the available command, as a reply to a valid link. 167 | 168 | * if file is larger than 1500MB, [read this](https://t.me/c/1434259219/113). 169 | 170 | * if file is a TAR archive, [read this](https://t.me/c/1434259219/104) to know how to uncompress. 171 | 172 | 173 | ## Credits, and Thanks to 174 | * [Dan Tès](https://telegram.dog/haskell) for his [Pyrogram Library](https://github.com/pyrogram/pyrogram) 175 | * [Robots](https://telegram.dog/Robots) for their [@UploadBot](https://telegram.dog/UploadBot) 176 | * [@AjeeshNair](https://telegram.dog/AjeeshNait) for his [torrent.ajee.sh](https://torrent.ajee.sh) 177 | * [@gotstc](https://telegram.dog/gotstc), @aryanvikash, [@HasibulKabir](https://telegram.dog/HasibulKabir) for their TORRENT groups 178 | * [![CopyLeft](https://telegra.ph/file/b514ed14d994557a724cb.jpg)](https://telegra.ph/file/fab1017e21c42a5c1e613.mp4 "CopyLeft Credit Video") 179 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/youtube_dl_extractor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot import ( 7 | DEF_THUMB_NAIL_VID_S 8 | ) 9 | import pyrogram 10 | import json 11 | from tobrot.helper_funcs.display_progress import humanbytes 12 | import asyncio 13 | import logging 14 | logging.basicConfig( 15 | level=logging.DEBUG, 16 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 17 | ) 18 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 19 | LOGGER = logging.getLogger(__name__) 20 | 21 | 22 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 23 | 24 | 25 | async def extract_youtube_dl_formats(url, yt_dl_user_name, yt_dl_pass_word, user_working_dir): 26 | command_to_exec = [ 27 | "youtube-dl", 28 | "--no-warnings", 29 | "--youtube-skip-dash-manifest", 30 | "-j", 31 | url 32 | ] 33 | if "hotstar" in url: 34 | command_to_exec.append("--geo-bypass-country") 35 | command_to_exec.append("IN") 36 | # 37 | if yt_dl_user_name is not None: 38 | command_to_exec.append("--username") 39 | command_to_exec.append(yt_dl_user_name) 40 | if yt_dl_pass_word is not None: 41 | command_to_exec.append("--password") 42 | command_to_exec.append(yt_dl_pass_word) 43 | 44 | LOGGER.info(command_to_exec) 45 | process = await asyncio.create_subprocess_exec( 46 | *command_to_exec, 47 | # stdout must a pipe to be accessible as process.stdout 48 | stdout=asyncio.subprocess.PIPE, 49 | stderr=asyncio.subprocess.PIPE, 50 | ) 51 | # Wait for the subprocess to finish 52 | stdout, stderr = await process.communicate() 53 | e_response = stderr.decode().strip() 54 | LOGGER.info(e_response) 55 | t_response = stdout.decode().strip() 56 | LOGGER.info(t_response) 57 | # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239 58 | if e_response: 59 | # logger.warn("Status : FAIL", exc.returncode, exc.output) 60 | error_message = e_response.replace( 61 | "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.", 62 | "") 63 | return None, error_message, None 64 | if t_response: 65 | # logger.info(t_response) 66 | x_reponse = t_response 67 | response_json = [] 68 | if "\n" in x_reponse: 69 | for yu_r in x_reponse.split("\n"): 70 | response_json.append(json.loads(yu_r)) 71 | else: 72 | response_json.append(json.loads(x_reponse)) 73 | # response_json = json.loads(x_reponse) 74 | save_ytdl_json_path = user_working_dir + \ 75 | "/" + str("ytdleech") + ".json" 76 | with open(save_ytdl_json_path, "w", encoding="utf8") as outfile: 77 | json.dump(response_json, outfile, ensure_ascii=False) 78 | # logger.info(response_json) 79 | inline_keyboard = [] 80 | # 81 | thumb_image = DEF_THUMB_NAIL_VID_S 82 | # 83 | for current_r_json in response_json: 84 | # 85 | thumb_image = current_r_json.get("thumbnail", thumb_image) 86 | # 87 | duration = None 88 | if "duration" in current_r_json: 89 | duration = current_r_json["duration"] 90 | if "formats" in current_r_json: 91 | for formats in current_r_json["formats"]: 92 | format_id = formats.get("format_id") 93 | format_string = formats.get("format_note") 94 | if format_string is None: 95 | format_string = formats.get("format") 96 | format_ext = formats.get("ext") 97 | approx_file_size = "" 98 | if "filesize" in formats: 99 | approx_file_size = humanbytes(formats["filesize"]) 100 | dipslay_str_uon = " " + format_string + \ 101 | " (" + format_ext.upper() + ") " + approx_file_size + " " 102 | cb_string_video = "{}|{}|{}".format( 103 | "video", format_id, format_ext) 104 | ikeyboard = [] 105 | if ( 106 | "drive.google.com" in url 107 | and format_id == "source" 108 | or "drive.google.com" not in url 109 | and format_string is not None 110 | and "audio only" not in format_string 111 | ): 112 | ikeyboard = [ 113 | pyrogram.InlineKeyboardButton( 114 | dipslay_str_uon, 115 | callback_data=(cb_string_video).encode("UTF-8") 116 | ) 117 | ] 118 | elif "drive.google.com" not in url: 119 | # special weird case :\ 120 | ikeyboard = [ 121 | pyrogram.InlineKeyboardButton( 122 | "SVideo [" + 123 | "] ( " + 124 | approx_file_size + " )", 125 | callback_data=(cb_string_video).encode("UTF-8") 126 | ) 127 | ] 128 | inline_keyboard.append(ikeyboard) 129 | if duration is not None: 130 | cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3") 131 | cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3") 132 | cb_string = "{}|{}|{}".format("audio", "320k", "mp3") 133 | inline_keyboard.append([ 134 | pyrogram.InlineKeyboardButton( 135 | "MP3 " + "(" + "64 kbps" + ")", callback_data=cb_string_64.encode("UTF-8")), 136 | pyrogram.InlineKeyboardButton( 137 | "MP3 " + "(" + "128 kbps" + ")", callback_data=cb_string_128.encode("UTF-8")) 138 | ]) 139 | inline_keyboard.append([pyrogram.InlineKeyboardButton( 140 | "MP3 " + "(" + "320 kbps" + ")", callback_data=cb_string.encode("UTF-8"))]) 141 | else: 142 | format_id = current_r_json["format_id"] 143 | format_ext = current_r_json["ext"] 144 | cb_string_video = "{}|{}|{}".format( 145 | "video", format_id, format_ext) 146 | inline_keyboard.append([ 147 | pyrogram.InlineKeyboardButton( 148 | "SVideo", 149 | callback_data=(cb_string_video).encode("UTF-8") 150 | ) 151 | ]) 152 | break 153 | reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard) 154 | # LOGGER.info(reply_markup) 155 | succss_mesg = """Select the desired format: 👇 156 | mentioned file size might be approximate""" 157 | return thumb_image, succss_mesg, reply_markup 158 | -------------------------------------------------------------------------------- /tobrot/plugins/status_message_fn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | # the logging things 6 | from tobrot.helper_funcs.upload_to_tg import upload_to_tg 7 | from tobrot.helper_funcs.download_aria_p_n import aria_start 8 | from tobrot.helper_funcs.admin_check import AdminCheck 9 | from tobrot import ( 10 | MAX_MESSAGE_LENGTH 11 | ) 12 | import time 13 | import os 14 | import asyncio 15 | import logging 16 | logging.basicConfig( 17 | level=logging.DEBUG, 18 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 19 | ) 20 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 21 | LOGGER = logging.getLogger(__name__) 22 | 23 | 24 | async def status_message_f(client, message): 25 | if not await AdminCheck(client, message.chat.id, message.from_user.id): 26 | return 27 | 28 | aria_i_p = await aria_start() 29 | # Show All Downloads 30 | downloads = aria_i_p.get_downloads() 31 | # 32 | DOWNLOAD_ICON = "📥" 33 | UPLOAD_ICON = "📤" 34 | # 35 | msg = "" 36 | for download in downloads: 37 | downloading_dir_name = "NA" 38 | try: 39 | downloading_dir_name = str(download.name) 40 | except BaseException: 41 | pass 42 | total_length_size = str(download.total_length_string()) 43 | progress_percent_string = str(download.progress_string()) 44 | down_speed_string = str(download.download_speed_string()) 45 | up_speed_string = str(download.upload_speed_string()) 46 | download_current_status = str(download.status) 47 | e_t_a = str(download.eta_string()) 48 | current_gid = str(download.gid) 49 | # 50 | msg += f"{downloading_dir_name}" 51 | msg += " | " 52 | msg += f"{total_length_size}" 53 | msg += " | " 54 | msg += f"{progress_percent_string}" 55 | msg += " | " 56 | msg += f"{DOWNLOAD_ICON} {down_speed_string}" 57 | msg += " | " 58 | msg += f"{UPLOAD_ICON} {up_speed_string}" 59 | msg += " | " 60 | msg += f"{e_t_a}" 61 | msg += " | " 62 | msg += f"{download_current_status}" 63 | msg += " | " 64 | msg += f"GID: {current_gid}" 65 | msg += " | " 66 | msg += "\n\n" 67 | LOGGER.info(msg) 68 | if msg == "": 69 | msg = "🤷‍♂️ No Active, Queued or Paused TORRENTs" 70 | await message.reply_text(msg, quote=True) 71 | 72 | 73 | async def cancel_message_f(client, message): 74 | if len(message.command) > 1: 75 | # /cancel command 76 | i_m_s_e_g = await message.reply_text("checking..?", quote=True) 77 | aria_i_p = await aria_start() 78 | g_id = message.command[1].strip() 79 | LOGGER.info(g_id) 80 | try: 81 | downloads = aria_i_p.get_download(g_id) 82 | LOGGER.info(downloads) 83 | LOGGER.info(downloads.remove(force=True)) 84 | await i_m_s_e_g.edit_text( 85 | "Mirror Cancelled" 86 | ) 87 | except Exception as e: 88 | await i_m_s_e_g.edit_text( 89 | "FAILED\n\n" + str(e) + "\n#error" 90 | ) 91 | else: 92 | await message.delete() 93 | 94 | 95 | async def exec_message_f(client, message): 96 | if not await AdminCheck(client, message.chat.id, message.from_user.id): 97 | return 98 | PROCESS_RUN_TIME = 100 99 | cmd = message.text.split(" ", maxsplit=1)[1] 100 | 101 | reply_to_id = message.message_id 102 | if message.reply_to_message: 103 | reply_to_id = message.reply_to_message.message_id 104 | 105 | time.time() + PROCESS_RUN_TIME 106 | process = await asyncio.create_subprocess_shell( 107 | cmd, 108 | stdout=asyncio.subprocess.PIPE, 109 | stderr=asyncio.subprocess.PIPE 110 | ) 111 | stdout, stderr = await process.communicate() 112 | e = stderr.decode() 113 | if not e: 114 | e = "No Error" 115 | o = stdout.decode() 116 | if not o: 117 | o = "No Output" 118 | else: 119 | _o = o.split("\n") 120 | o = "`\n".join(_o) 121 | OUTPUT = f"**QUERY:**\n__Command:__\n`{cmd}` \n__PID:__\n`{process.pid}`\n\n**stderr:** \n`{e}`\n**Output:**\n{o}" 122 | 123 | if len(OUTPUT) > MAX_MESSAGE_LENGTH: 124 | with open("exec.text", "w+", encoding="utf8") as out_file: 125 | out_file.write(str(OUTPUT)) 126 | await client.send_document( 127 | chat_id=message.chat.id, 128 | document="exec.text", 129 | caption=cmd, 130 | disable_notification=True, 131 | reply_to_message_id=reply_to_id 132 | ) 133 | os.remove("exec.text") 134 | await message.delete() 135 | else: 136 | await message.reply_text(OUTPUT) 137 | 138 | 139 | async def upload_document_f(client, message): 140 | imsegd = await message.reply_text( 141 | "processing ..." 142 | ) 143 | if ( 144 | await AdminCheck(client, message.chat.id, message.from_user.id) 145 | and " " in message.text 146 | ): 147 | recvd_command, local_file_name = message.text.split(" ", 1) 148 | recvd_response = await upload_to_tg( 149 | imsegd, 150 | local_file_name, 151 | message.from_user.id, 152 | {} 153 | ) 154 | LOGGER.info(recvd_response) 155 | await imsegd.delete() 156 | ''' 157 | async def eval_message_f(client, message): 158 | status_message = await message.reply_text("Processing ...") 159 | cmd = message.text.split(" ", maxsplit=1)[1] 160 | 161 | reply_to_id = message.message_id 162 | if message.reply_to_message: 163 | reply_to_id = message.reply_to_message.message_id 164 | 165 | old_stderr = sys.stderr 166 | old_stdout = sys.stdout 167 | redirected_output = sys.stdout = io.StringIO() 168 | redirected_error = sys.stderr = io.StringIO() 169 | stdout, stderr, exc = None, None, None 170 | 171 | try: 172 | await aexec(cmd, client, message) 173 | except Exception: 174 | exc = traceback.format_exc() 175 | 176 | stdout = redirected_output.getvalue() 177 | stderr = redirected_error.getvalue() 178 | sys.stdout = old_stdout 179 | sys.stderr = old_stderr 180 | 181 | evaluation = "" 182 | if exc: 183 | evaluation = exc 184 | elif stderr: 185 | evaluation = stderr 186 | elif stdout: 187 | evaluation = stdout 188 | else: 189 | evaluation = "Success" 190 | 191 | final_output = "EVAL: {}\n\nOUTPUT:\n{} \n".format( 192 | cmd, 193 | evaluation.strip() 194 | ) 195 | 196 | if len(final_output) > MAX_MESSAGE_LENGTH: 197 | with open("eval.text", "w+", encoding="utf8") as out_file: 198 | out_file.write(str(final_output)) 199 | await message.reply_document( 200 | document="eval.text", 201 | caption=cmd, 202 | disable_notification=True, 203 | reply_to_message_id=reply_to_id 204 | ) 205 | os.remove("eval.text") 206 | await status_message.delete() 207 | else: 208 | await status_message.edit(final_output) 209 | 210 | 211 | async def aexec(code, client, message): 212 | exec( 213 | f'async def __aexec(client, message): ' + 214 | ''.join(f'\n {l}' for l in code.split('\n')) 215 | ) 216 | return await locals()['__aexec'](client, message) 217 | ''' 218 | -------------------------------------------------------------------------------- /tobrot/plugins/incoming_message_fn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 | Akshay C 4 | 5 | # the logging things 6 | from tobrot.helper_funcs.admin_check import AdminCheck 7 | from tobrot.helper_funcs.youtube_dl_extractor import extract_youtube_dl_formats 8 | from tobrot.helper_funcs.download_aria_p_n import call_apropriate_function, call_apropriate_function_g, aria_start 9 | from tobrot.helper_funcs.extract_link_from_message import extract_link 10 | import time 11 | from tobrot import ( 12 | DOWNLOAD_LOCATION 13 | ) 14 | import os 15 | import logging 16 | logging.basicConfig( 17 | level=logging.DEBUG, 18 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 19 | ) 20 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 21 | LOGGER = logging.getLogger(__name__) 22 | 23 | 24 | async def incoming_purge_message_f(client, message): 25 | """/purge command""" 26 | i_m_sefg2 = await message.reply_text("Purging...", quote=True) 27 | if await AdminCheck(client, message.chat.id, message.from_user.id): 28 | aria_i_p = await aria_start() 29 | # Show All Downloads 30 | downloads = aria_i_p.get_downloads() 31 | for download in downloads: 32 | LOGGER.info(download.remove(force=True)) 33 | await i_m_sefg2.delete() 34 | 35 | 36 | async def incoming_message_f(client, message): 37 | """/leech command""" 38 | i_m_sefg = await message.reply_text("processing", quote=True) 39 | is_zip = False 40 | is_unzip = False 41 | is_unrar = False 42 | is_untar = False 43 | if len(message.command) > 1: 44 | if message.command[1] == "archive": 45 | is_zip = True 46 | elif message.command[1] == "unzip": 47 | is_unzip = True 48 | elif message.command[1] == "unrar": 49 | is_unrar = True 50 | elif message.command[1] == "untar": 51 | is_untar = True 52 | # get link from the incoming message 53 | dl_url, cf_name, _, _ = await extract_link(message.reply_to_message, "LEECH") 54 | LOGGER.info(dl_url) 55 | LOGGER.info(cf_name) 56 | if dl_url is not None: 57 | await i_m_sefg.edit_text("extracting links") 58 | # start the aria2c daemon 59 | aria_i_p = await aria_start() 60 | LOGGER.info(aria_i_p) 61 | current_user_id = message.from_user.id 62 | # create an unique directory 63 | new_download_location = os.path.join( 64 | DOWNLOAD_LOCATION, 65 | str(current_user_id), 66 | str(time.time()) 67 | ) 68 | # create download directory, if not exist 69 | if not os.path.isdir(new_download_location): 70 | os.makedirs(new_download_location) 71 | await i_m_sefg.edit_text("trying to download") 72 | # try to download the "link" 73 | sagtus, err_message = await call_apropriate_function( 74 | aria_i_p, 75 | dl_url, 76 | new_download_location, 77 | i_m_sefg, 78 | is_zip, 79 | cf_name, 80 | is_unzip, 81 | is_unrar, 82 | is_untar, 83 | message 84 | ) 85 | if not sagtus: 86 | # if FAILED, display the error message 87 | await i_m_sefg.edit_text(err_message) 88 | else: 89 | await i_m_sefg.edit_text( 90 | "**Reply sar,reply to any message link. \nPlease read /help \n" 91 | f"API Error: {cf_name}" 92 | ) 93 | # 94 | 95 | 96 | async def incoming_gdrive_message_f(client, message): 97 | """/gleech command""" 98 | i_m_sefg = await message.reply_text("processing", quote=True) 99 | is_zip = False 100 | is_unzip = False 101 | is_unrar = False 102 | is_untar = False 103 | if len(message.command) > 1: 104 | if message.command[1] == "archive": 105 | is_zip = True 106 | elif message.command[1] == "unzip": 107 | is_unzip = True 108 | elif message.command[1] == "unrar": 109 | is_unrar = True 110 | elif message.command[1] == "untar": 111 | is_untar = True 112 | # get link from the incoming message 113 | dl_url, cf_name, _, _ = await extract_link(message.reply_to_message, "GLEECH") 114 | LOGGER.info(dl_url) 115 | LOGGER.info(cf_name) 116 | if dl_url is not None: 117 | await i_m_sefg.edit_text("extracting links") 118 | # start the aria2c daemon 119 | aria_i_p = await aria_start() 120 | LOGGER.info(aria_i_p) 121 | current_user_id = message.from_user.id 122 | # create an unique directory 123 | new_download_location = os.path.join( 124 | DOWNLOAD_LOCATION, 125 | str(current_user_id), 126 | str(time.time()) 127 | ) 128 | # create download directory, if not exist 129 | if not os.path.isdir(new_download_location): 130 | os.makedirs(new_download_location) 131 | await i_m_sefg.edit_text("trying to download") 132 | # try to download the "link" 133 | await call_apropriate_function_g( 134 | aria_i_p, 135 | dl_url, 136 | new_download_location, 137 | i_m_sefg, 138 | is_zip, 139 | cf_name, 140 | is_unzip, 141 | is_unrar, 142 | is_untar, 143 | message 144 | ) 145 | else: 146 | await i_m_sefg.edit_text( 147 | "**Reply sar,reply to any message link. \nPlease read /help \n" 148 | f"API Error: {cf_name}" 149 | ) 150 | 151 | 152 | async def incoming_youtube_dl_f(client, message): 153 | """ /ytdl command """ 154 | i_m_sefg = await message.reply_text("processing", quote=True) 155 | # LOGGER.info(message) 156 | # extract link from message 157 | dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link( 158 | message.reply_to_message, "YTDL" 159 | ) 160 | LOGGER.info(dl_url) 161 | if len(message.command) > 1 and message.command[1] == "gdrive": 162 | with open('blame_my_knowledge.txt', 'w+') as gg: 163 | gg.write( 164 | "I am noob and don't know what to do that's why I have did this") 165 | LOGGER.info(cf_name) 166 | if dl_url is not None: 167 | await i_m_sefg.edit_text("extracting links") 168 | current_user_id = message.from_user.id 169 | # create an unique directory 170 | user_working_dir = os.path.join( 171 | DOWNLOAD_LOCATION, str(current_user_id)) 172 | # create download directory, if not exist 173 | if not os.path.isdir(user_working_dir): 174 | os.makedirs(user_working_dir) 175 | # list the formats, and display in button markup formats 176 | thumb_image, text_message, reply_markup = await extract_youtube_dl_formats( 177 | dl_url, 178 | # cf_name, 179 | yt_dl_user_name, 180 | yt_dl_pass_word, 181 | user_working_dir 182 | ) 183 | if thumb_image is not None: 184 | await message.reply_photo( 185 | photo=thumb_image, 186 | quote=True, 187 | caption=text_message, 188 | reply_markup=reply_markup 189 | ) 190 | await i_m_sefg.delete() 191 | else: 192 | await i_m_sefg.edit_text( 193 | text=text_message, 194 | reply_markup=reply_markup 195 | ) 196 | else: 197 | await i_m_sefg.edit_text( 198 | "Reply sar,reply to any message link. \nPlease read /help \n" 199 | f"API Error: {cf_name}" 200 | ) 201 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/youtube_dl_button.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | # the logging things 6 | from tobrot.helper_funcs.upload_to_tg import upload_to_tg, upload_to_gdrive 7 | from tobrot import ( 8 | DOWNLOAD_LOCATION, 9 | AUTH_CHANNEL 10 | ) 11 | from datetime import datetime 12 | import subprocess 13 | import shutil 14 | import os 15 | import json 16 | import asyncio 17 | import logging 18 | logging.basicConfig( 19 | level=logging.DEBUG, 20 | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') 21 | LOGGER = logging.getLogger(__name__) 22 | 23 | 24 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 25 | 26 | 27 | async def youtube_dl_call_back(bot, update): 28 | LOGGER.info(update) 29 | cb_data = update.data 30 | # youtube_dl extractors 31 | tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|") 32 | # 33 | current_user_id = update.message.reply_to_message.from_user.id 34 | current_touched_user_id = update.from_user.id 35 | if current_user_id != current_touched_user_id: 36 | await bot.answer_callback_query( 37 | callback_query_id=update.id, 38 | text="who are you? 🤪🤔🤔🤔", 39 | show_alert=True, 40 | cache_time=0 41 | ) 42 | return False, None 43 | 44 | user_working_dir = os.path.join(DOWNLOAD_LOCATION, str(current_user_id)) 45 | # create download directory, if not exist 46 | if not os.path.isdir(user_working_dir): 47 | await bot.delete_messages( 48 | chat_id=update.message.chat.id, 49 | message_ids=[ 50 | update.message.message_id, 51 | update.message.reply_to_message.message_id, 52 | ], 53 | revoke=True 54 | ) 55 | return 56 | save_ytdl_json_path = user_working_dir + \ 57 | "/" + str("ytdleech") + ".json" 58 | try: 59 | with open(save_ytdl_json_path, "r", encoding="utf8") as f: 60 | response_json = json.load(f) 61 | os.remove(save_ytdl_json_path) 62 | except (FileNotFoundError): 63 | await bot.delete_messages( 64 | chat_id=update.message.chat.id, 65 | message_ids=[ 66 | update.message.message_id, 67 | update.message.reply_to_message.message_id, 68 | ], 69 | revoke=True 70 | ) 71 | return False 72 | # 73 | response_json = response_json[0] 74 | # TODO: temporary limitations 75 | # LOGGER.info(response_json) 76 | # 77 | youtube_dl_url = response_json.get("webpage_url") 78 | LOGGER.info(youtube_dl_url) 79 | # 80 | custom_file_name = "%(title)s.%(ext)s" 81 | # https://superuser.com/a/994060 82 | LOGGER.info(custom_file_name) 83 | # 84 | await update.message.edit_caption( 85 | caption="trying to download" 86 | ) 87 | description = "@PublicLeech" 88 | if "fulltitle" in response_json: 89 | description = response_json["fulltitle"][0:1021] 90 | # escape Markdown and special characters 91 | # 92 | tmp_directory_for_each_user = os.path.join( 93 | DOWNLOAD_LOCATION, 94 | str(update.from_user.id) 95 | ) 96 | if not os.path.isdir(tmp_directory_for_each_user): 97 | os.makedirs(tmp_directory_for_each_user) 98 | download_directory = tmp_directory_for_each_user 99 | download_directory = os.path.join( 100 | tmp_directory_for_each_user, custom_file_name) 101 | command_to_exec = [] 102 | if tg_send_type == "audio": 103 | command_to_exec = [ 104 | "youtube-dl", 105 | "-c", 106 | "--prefer-ffmpeg", 107 | "--extract-audio", 108 | "--audio-format", youtube_dl_ext, 109 | "--audio-quality", youtube_dl_format, 110 | youtube_dl_url, 111 | "-o", download_directory, 112 | # "--external-downloader", "aria2c" 113 | ] 114 | else: 115 | # command_to_exec = ["youtube-dl", "-f", youtube_dl_format, "--hls-prefer-ffmpeg", "--recode-video", "mp4", "-k", youtube_dl_url, "-o", download_directory] 116 | minus_f_format = youtube_dl_format 117 | if "youtu" in youtube_dl_url: 118 | for for_mat in response_json["formats"]: 119 | format_id = for_mat.get("format_id") 120 | if format_id == youtube_dl_format: 121 | acodec = for_mat.get("acodec") 122 | vcodec = for_mat.get("vcodec") 123 | if acodec == "none" or vcodec == "none": 124 | minus_f_format = youtube_dl_format + "+bestaudio" 125 | break 126 | command_to_exec = [ 127 | "youtube-dl", 128 | "-c", 129 | "--embed-subs", 130 | "-f", minus_f_format, 131 | "--hls-prefer-ffmpeg", youtube_dl_url, 132 | "-o", download_directory, 133 | # "--external-downloader", "aria2c" 134 | ] 135 | # 136 | command_to_exec.append("--no-warnings") 137 | # command_to_exec.append("--quiet") 138 | command_to_exec.append("--restrict-filenames") 139 | # 140 | if "hotstar" in youtube_dl_url: 141 | command_to_exec.append("--geo-bypass-country") 142 | command_to_exec.append("IN") 143 | LOGGER.info(command_to_exec) 144 | start = datetime.now() 145 | process = await asyncio.create_subprocess_exec( 146 | *command_to_exec, 147 | # stdout must a pipe to be accessible as process.stdout 148 | stdout=asyncio.subprocess.PIPE, 149 | stderr=asyncio.subprocess.PIPE, 150 | ) 151 | # Wait for the subprocess to finish 152 | stdout, stderr = await process.communicate() 153 | e_response = stderr.decode().strip() 154 | t_response = stdout.decode().strip() 155 | # LOGGER.info(e_response) 156 | # LOGGER.info(t_response) 157 | ad_string_to_replace = "please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output." 158 | if e_response and ad_string_to_replace in e_response: 159 | error_message = e_response.replace(ad_string_to_replace, "") 160 | await update.message.edit_caption( 161 | caption=error_message 162 | ) 163 | return False, None 164 | if t_response: 165 | # LOGGER.info(t_response) 166 | # os.remove(save_ytdl_json_path) 167 | end_one = datetime.now() 168 | (end_one - start).seconds 169 | dir_contents = len(os.listdir(tmp_directory_for_each_user)) 170 | # dir_contents.sort() 171 | await update.message.edit_caption( 172 | caption=f"found {dir_contents} files" 173 | ) 174 | user_id = update.from_user.id 175 | # 176 | print(tmp_directory_for_each_user) 177 | if os.path.exists('blame_my_knowledge.txt'): 178 | for a, b, c in os.walk(tmp_directory_for_each_user): 179 | print(a) 180 | for d in c: 181 | e = os.path.join(a, d) 182 | print(e) 183 | gaut_am = os.path.basename(e) 184 | print(gaut_am) 185 | liop = subprocess.Popen( 186 | ["mv", f'{e}', "/app/"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) 187 | o, e = liop.communicate() 188 | print(o) 189 | print(e) 190 | final_response = await upload_to_gdrive( 191 | gaut_am, 192 | update.message, 193 | update.message.reply_to_message, 194 | user_id 195 | ) 196 | else: 197 | final_response = await upload_to_tg( 198 | update.message, 199 | tmp_directory_for_each_user, 200 | user_id, 201 | {}, 202 | True 203 | ) 204 | 205 | ''' 206 | final_response = await upload_to_tg( 207 | update.message, 208 | tmp_directory_for_each_user, 209 | user_id, 210 | {}, 211 | True 212 | ) 213 | ''' 214 | LOGGER.info(final_response) 215 | # 216 | try: 217 | shutil.rmtree(tmp_directory_for_each_user) 218 | os.remove('blame_my_knowledge.txt') 219 | except BaseException: 220 | pass 221 | # 222 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/upload_to_tg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | # the logging things 6 | from pyrogram import ( 7 | InputMediaDocument, 8 | InputMediaVideo, 9 | InputMediaAudio 10 | ) 11 | from tobrot import ( 12 | TG_MAX_FILE_SIZE, 13 | DOWNLOAD_LOCATION, 14 | DESTINATION_FOLDER, 15 | RCLONE_CONFIG, 16 | INDEX_LINK 17 | ) 18 | from tobrot.helper_funcs.copy_similar_file import copy_file 19 | from tobrot.helper_funcs.split_large_files import split_large_files 20 | from tobrot.helper_funcs.help_Nekmo_ffmpeg import take_screen_shot 21 | from tobrot.helper_funcs.display_progress import progress_for_pyrogram, humanbytes 22 | from PIL import Image 23 | from hachoir.parser import createParser 24 | from hachoir.metadata import extractMetadata 25 | from hurry.filesize import size 26 | import requests 27 | import re 28 | import subprocess 29 | import time 30 | import os 31 | import asyncio 32 | import logging 33 | logging.basicConfig( 34 | level=logging.DEBUG, 35 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 36 | ) 37 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 38 | LOGGER = logging.getLogger(__name__) 39 | 40 | 41 | # stackoverflow🤐 42 | 43 | 44 | def getFolderSize(p): 45 | from functools import partial 46 | prepend = partial(os.path.join, p) 47 | return sum( 48 | os.path.getsize(f) if os.path.isfile(f) else getFolderSize(f) 49 | for f in map(prepend, os.listdir(p)) 50 | ) 51 | 52 | 53 | async def upload_to_tg( 54 | message, 55 | local_file_name, 56 | from_user, 57 | dict_contatining_uploaded_files, 58 | edit_media=False 59 | ): 60 | LOGGER.info(local_file_name) 61 | base_file_name = os.path.basename(local_file_name) 62 | caption_str = "" 63 | caption_str += "" 64 | caption_str += base_file_name 65 | caption_str += "" 66 | # caption_str += "\n\n" 67 | # caption_str += "" 70 | # caption_str += "Here is the file to the link you sent" 71 | # caption_str += "" 72 | if os.path.isdir(local_file_name): 73 | directory_contents = os.listdir(local_file_name) 74 | directory_contents.sort() 75 | # number_of_files = len(directory_contents) 76 | LOGGER.info(directory_contents) 77 | new_m_esg = message 78 | if not new_m_esg.photo: 79 | new_m_esg = await message.reply_text( 80 | "Found {} files".format(len(directory_contents)), 81 | quote=True 82 | # reply_to_message_id=message.message_id 83 | ) 84 | for single_file in directory_contents: 85 | # recursion: will this FAIL somewhere? 86 | await upload_to_tg( 87 | new_m_esg, 88 | os.path.join(local_file_name, single_file), 89 | from_user, 90 | dict_contatining_uploaded_files, 91 | edit_media 92 | ) 93 | else: 94 | if os.path.getsize(local_file_name) > TG_MAX_FILE_SIZE: 95 | LOGGER.info("TODO") 96 | d_f_s = humanbytes(os.path.getsize(local_file_name)) 97 | i_m_s_g = await message.reply_text( 98 | "Telegram does not support uploading this file.\n" 99 | f"Detected File Size: {d_f_s} \n" 100 | "\ntrying to split the files" 101 | ) 102 | splitted_dir = await split_large_files(local_file_name) 103 | totlaa_sleif = os.listdir(splitted_dir) 104 | totlaa_sleif.sort() 105 | number_of_files = len(totlaa_sleif) 106 | LOGGER.info(totlaa_sleif) 107 | ba_se_file_name = os.path.basename(local_file_name) 108 | await i_m_s_g.edit_text( 109 | f"Detected File Size: {d_f_s} \n" 110 | f"{ba_se_file_name} splitted into {number_of_files} files.\n" 111 | "trying to upload to Telegram, now ..." 112 | ) 113 | for le_file in totlaa_sleif: 114 | # recursion: will this FAIL somewhere? 115 | await upload_to_tg( 116 | message, 117 | os.path.join(splitted_dir, le_file), 118 | from_user, 119 | dict_contatining_uploaded_files 120 | ) 121 | else: 122 | sent_message = await upload_single_file( 123 | message, 124 | local_file_name, 125 | caption_str, 126 | from_user, 127 | edit_media 128 | ) 129 | if sent_message is not None: 130 | dict_contatining_uploaded_files[os.path.basename( 131 | local_file_name)] = sent_message.message_id 132 | # await message.delete() 133 | return dict_contatining_uploaded_files 134 | # 135 | 136 | 137 | async def upload_to_gdrive(file_upload, message, messa_ge, g_id): 138 | await asyncio.sleep(5) 139 | await message.edit_text("Uploading...") 140 | start_time = int(round(time.time() * 1)) 141 | subprocess.Popen(('touch', 'rclone.conf'), stdout=subprocess.PIPE) 142 | with open('rclone.conf', 'a', newline="\n") as fole: 143 | fole.write("[DRIVE]\n") 144 | fole.write(f"{RCLONE_CONFIG}") 145 | destination = f'{DESTINATION_FOLDER}' 146 | if os.path.isfile(file_upload): 147 | tmp = subprocess.Popen(['rclone', 148 | 'copy', 149 | '--config=rclone.conf', 150 | f'{file_upload}', 151 | 'DRIVE:' 152 | f'{destination}', 153 | '-v'], 154 | stdout=subprocess.PIPE) 155 | pro, cess = tmp.communicate() 156 | gk_file = re.escape(file_upload) 157 | print(gk_file) 158 | with open('filter.txt', 'w+') as filter: 159 | print(f"+ {gk_file}\n- *", file=filter) 160 | process1 = subprocess.Popen(['rclone', 161 | 'lsf', 162 | '--config=rclone.conf', 163 | '-F', 164 | 'i', 165 | "--filter-from=filter.txt", 166 | "--files-only", 167 | 'DRIVE:' 168 | f'{destination}'], 169 | stdout=subprocess.PIPE, 170 | stderr=subprocess.PIPE) 171 | # os.remove("filter.txt") 172 | popi, popp = process1.communicate() 173 | print(popi) 174 | p = popi.decode("utf-8") 175 | print(p) 176 | # os.remove("filter.txt") 177 | gauti = f"https://drive.google.com/file/d/{p}/view?usp=drivesdk" 178 | gau_link = re.search(r"(?Phttps?://[^\s]+)", gauti).group("url") 179 | print(gau_link) 180 | indexurl = f"{INDEX_LINK}/{file_upload}" 181 | tam_link = requests.utils.requote_uri(indexurl) 182 | #s_tr = '-'*40 183 | gjay = size(os.path.getsize(file_upload)) 184 | print(gjay) 185 | end_time = int(round(time.time() * 1)) 186 | m_s = (end_time - start_time) 187 | await message.edit_text(f"""**Uploaded Successfully** __in {m_s}seconds__ \n\n📄 {file_upload} ({gjay})""") 188 | os.remove(file_upload) 189 | else: 190 | tt = os.path.join(destination, file_upload) 191 | print(tt) 192 | tmp = subprocess.Popen(['rclone', 193 | 'copy', 194 | '--config=rclone.conf', 195 | f'{file_upload}', 196 | 'DRIVE:' 197 | f'{tt}', 198 | '-v'], 199 | stdout=subprocess.PIPE) 200 | pro, cess = tmp.communicate() 201 | print(pro) 202 | g_file = re.escape(file_upload) 203 | print(g_file) 204 | with open('filter1.txt', 'w+') as filter1: 205 | print(f"+ {g_file}/\n- *", file=filter1) 206 | process12 = subprocess.Popen(['rclone', 207 | 'lsf', 208 | '--config=rclone.conf', 209 | '-F', 210 | 'i', 211 | "--filter-from=filter1.txt", 212 | "--dirs-only", 213 | 'DRIVE:' 214 | f'{destination}'], 215 | stdout=subprocess.PIPE, 216 | stderr=subprocess.PIPE) 217 | # os.remove("filter1.txt") 218 | popie, popp = process12.communicate() 219 | print(popie) 220 | p = popie.decode("utf-8") 221 | print(p) 222 | # os.remove("filter1.txt") 223 | gautii = f"https://drive.google.com/folderview?id={p}" 224 | gau_link = re.search(r"(?Phttps?://[^\s]+)", gautii).group("url") 225 | print(gau_link) 226 | indexurl = f"{INDEX_LINK}/{file_upload}/" 227 | tam_link = requests.utils.requote_uri(indexurl) 228 | gjay = size(os.path.getsize(file_upload)) 229 | print(gjay) 230 | #s_tr = '-'*40 231 | end_time = int(round(time.time() * 1)) 232 | m_s = (end_time - start_time) 233 | await message.edit_text(f"""**Uploaded Successfully** __in {m_s}seconds__ \n\n📁 {file_upload} ({gjay})""") 234 | 235 | # 236 | 237 | 238 | async def upload_single_file(message, local_file_name, caption_str, from_user, edit_media): 239 | sent_message = None 240 | start_time = time.time() 241 | # 242 | thumbnail_location = os.path.join( 243 | DOWNLOAD_LOCATION, 244 | "thumbnails", 245 | str(from_user) + ".jpg" 246 | ) 247 | LOGGER.info(thumbnail_location) 248 | # 249 | try: 250 | message_for_progress_display = message 251 | if not edit_media: 252 | message_for_progress_display = await message.reply_text( 253 | "starting upload of {}".format(os.path.basename(local_file_name)) 254 | ) 255 | if local_file_name.upper().endswith(("MKV", "MP4", "WEBM")): 256 | metadata = extractMetadata(createParser(local_file_name)) 257 | duration = 0 258 | if metadata.has("duration"): 259 | duration = metadata.get('duration').seconds 260 | # 261 | width = 0 262 | height = 0 263 | thumb_image_path = None 264 | if os.path.exists(thumbnail_location): 265 | thumb_image_path = await copy_file( 266 | thumbnail_location, 267 | os.path.dirname(os.path.abspath(local_file_name)) 268 | ) 269 | else: 270 | thumb_image_path = await take_screen_shot( 271 | local_file_name, 272 | os.path.dirname(os.path.abspath(local_file_name)), 273 | (duration / 2) 274 | ) 275 | # get the correct width, height, and duration for videos 276 | # greater than 10MB 277 | if os.path.exists(thumb_image_path): 278 | metadata = extractMetadata(createParser(thumb_image_path)) 279 | if metadata.has("width"): 280 | width = metadata.get("width") 281 | if metadata.has("height"): 282 | height = metadata.get("height") 283 | # resize image 284 | # ref: https://t.me/PyrogramChat/44663 285 | # https://stackoverflow.com/a/21669827/4723940 286 | Image.open(thumb_image_path).convert( 287 | "RGB" 288 | ).save(thumb_image_path) 289 | img = Image.open(thumb_image_path) 290 | # https://stackoverflow.com/a/37631799/4723940 291 | img.resize((320, height)) 292 | img.save(thumb_image_path, "JPEG") 293 | # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails 294 | # 295 | thumb = None 296 | if thumb_image_path is not None and os.path.isfile( 297 | thumb_image_path): 298 | thumb = thumb_image_path 299 | # send video 300 | if edit_media and message.photo: 301 | sent_message = await message.edit_media( 302 | media=InputMediaVideo( 303 | media=local_file_name, 304 | thumb=thumb, 305 | caption=caption_str, 306 | parse_mode="html", 307 | width=width, 308 | height=height, 309 | duration=duration, 310 | supports_streaming=True 311 | ) 312 | # quote=True, 313 | ) 314 | else: 315 | sent_message = await message.reply_video( 316 | video=local_file_name, 317 | # quote=True, 318 | caption=caption_str, 319 | parse_mode="html", 320 | duration=duration, 321 | width=width, 322 | height=height, 323 | thumb=thumb, 324 | supports_streaming=True, 325 | disable_notification=True, 326 | # reply_to_message_id=message.reply_to_message.message_id, 327 | progress=progress_for_pyrogram, 328 | progress_args=( 329 | "trying to upload", 330 | message_for_progress_display, 331 | start_time 332 | ) 333 | ) 334 | elif local_file_name.upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")): 335 | metadata = extractMetadata(createParser(local_file_name)) 336 | duration = 0 337 | title = "" 338 | artist = "" 339 | if metadata.has("duration"): 340 | duration = metadata.get('duration').seconds 341 | if metadata.has("title"): 342 | title = metadata.get("title") 343 | if metadata.has("artist"): 344 | artist = metadata.get("artist") 345 | thumb_image_path = None 346 | if os.path.isfile(thumbnail_location): 347 | thumb_image_path = await copy_file( 348 | thumbnail_location, 349 | os.path.dirname(os.path.abspath(local_file_name)) 350 | ) 351 | thumb = None 352 | if thumb_image_path is not None and os.path.isfile( 353 | thumb_image_path): 354 | thumb = thumb_image_path 355 | # send audio 356 | if edit_media and message.photo: 357 | sent_message = await message.edit_media( 358 | media=InputMediaAudio( 359 | media=local_file_name, 360 | thumb=thumb, 361 | caption=caption_str, 362 | parse_mode="html", 363 | duration=duration, 364 | performer=artist, 365 | title=title 366 | ) 367 | # quote=True, 368 | ) 369 | else: 370 | sent_message = await message.reply_audio( 371 | audio=local_file_name, 372 | # quote=True, 373 | caption=caption_str, 374 | parse_mode="html", 375 | duration=duration, 376 | performer=artist, 377 | title=title, 378 | thumb=thumb, 379 | disable_notification=True, 380 | # reply_to_message_id=message.reply_to_message.message_id, 381 | progress=progress_for_pyrogram, 382 | progress_args=( 383 | "trying to upload", 384 | message_for_progress_display, 385 | start_time 386 | ) 387 | ) 388 | else: 389 | thumb_image_path = None 390 | if os.path.isfile(thumbnail_location): 391 | thumb_image_path = await copy_file( 392 | thumbnail_location, 393 | os.path.dirname(os.path.abspath(local_file_name)) 394 | ) 395 | # if a file, don't upload "thumb" 396 | # this "diff" is a major derp -_- 😔😭😭 397 | thumb = None 398 | if thumb_image_path is not None and os.path.isfile( 399 | thumb_image_path): 400 | thumb = thumb_image_path 401 | # 402 | # send document 403 | if edit_media and message.photo: 404 | sent_message = await message.edit_media( 405 | media=InputMediaDocument( 406 | media=local_file_name, 407 | thumb=thumb, 408 | caption=caption_str, 409 | parse_mode="html" 410 | ) 411 | # quote=True, 412 | ) 413 | else: 414 | sent_message = await message.reply_document( 415 | document=local_file_name, 416 | # quote=True, 417 | thumb=thumb, 418 | caption=caption_str, 419 | parse_mode="html", 420 | disable_notification=True, 421 | # reply_to_message_id=message.reply_to_message.message_id, 422 | progress=progress_for_pyrogram, 423 | progress_args=( 424 | "trying to upload", 425 | message_for_progress_display, 426 | start_time 427 | ) 428 | ) 429 | if thumb is not None: 430 | os.remove(thumb) 431 | except Exception as e: 432 | await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) 433 | else: 434 | if message.message_id != message_for_progress_display.message_id: 435 | await message_for_progress_display.delete() 436 | os.remove(local_file_name) 437 | return sent_message 438 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/download_aria_p_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | # the logging things 6 | from pyrogram import ( 7 | InlineKeyboardButton, 8 | InlineKeyboardMarkup, 9 | Message 10 | ) 11 | from tobrot import ( 12 | ARIA_TWO_STARTED_PORT, 13 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START, 14 | AUTH_CHANNEL, 15 | DOWNLOAD_LOCATION, 16 | CUSTOM_FILE_NAME 17 | ) 18 | from tobrot.helper_funcs.create_compressed_archive import create_archive, unzip_me, unrar_me, untar_me 19 | from tobrot.helper_funcs.upload_to_tg import upload_to_tg, upload_to_gdrive 20 | import os 21 | import asyncio 22 | import aria2p 23 | import logging 24 | logging.basicConfig( 25 | level=logging.DEBUG, 26 | format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 27 | ) 28 | logging.getLogger("pyrogram").setLevel(logging.WARNING) 29 | LOGGER = logging.getLogger(__name__) 30 | 31 | 32 | async def aria_start(): 33 | aria2_daemon_start_cmd = [] 34 | # start the daemon, aria2c command 35 | aria2_daemon_start_cmd.append("aria2c") 36 | # aria2_daemon_start_cmd.append("--allow-overwrite=true") 37 | aria2_daemon_start_cmd.append("--daemon=true") 38 | # aria2_daemon_start_cmd.append(f"--dir={DOWNLOAD_LOCATION}") 39 | # TODO: this does not work, need to investigate this. 40 | # but for now, https://t.me/TrollVoiceBot?start=858 41 | aria2_daemon_start_cmd.append("--enable-rpc") 42 | aria2_daemon_start_cmd.append("--follow-torrent=mem") 43 | aria2_daemon_start_cmd.append("--max-connection-per-server=10") 44 | aria2_daemon_start_cmd.append("--min-split-size=10M") 45 | aria2_daemon_start_cmd.append("--rpc-listen-all=false") 46 | aria2_daemon_start_cmd.append(f"--rpc-listen-port={ARIA_TWO_STARTED_PORT}") 47 | aria2_daemon_start_cmd.append("--rpc-max-request-size=1024M") 48 | aria2_daemon_start_cmd.append("--seed-ratio=0.0") 49 | aria2_daemon_start_cmd.append("--seed-time=1") 50 | aria2_daemon_start_cmd.append("--split=10") 51 | aria2_daemon_start_cmd.append( 52 | f"--bt-stop-timeout={MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START}") 53 | # 54 | LOGGER.info(aria2_daemon_start_cmd) 55 | # 56 | process = await asyncio.create_subprocess_exec( 57 | *aria2_daemon_start_cmd, 58 | stdout=asyncio.subprocess.PIPE, 59 | stderr=asyncio.subprocess.PIPE 60 | ) 61 | stdout, stderr = await process.communicate() 62 | LOGGER.info(stdout) 63 | LOGGER.info(stderr) 64 | aria2 = aria2p.API( 65 | aria2p.Client( 66 | host="http://localhost", 67 | port=ARIA_TWO_STARTED_PORT, 68 | secret="" 69 | ) 70 | ) 71 | return aria2 72 | 73 | 74 | def add_magnet(aria_instance, magnetic_link, c_file_name): 75 | options = None 76 | # if c_file_name is not None: 77 | # options = { 78 | # "dir": c_file_name 79 | # } 80 | try: 81 | download = aria_instance.add_magnet( 82 | magnetic_link, 83 | options=options 84 | ) 85 | except Exception as e: 86 | return False, "**FAILED** \n" + \ 87 | str(e) + " \nPlease do not send SLOW links. Read /help" 88 | else: 89 | return True, "" + download.gid + "" 90 | 91 | 92 | def add_torrent(aria_instance, torrent_file_path): 93 | if torrent_file_path is None: 94 | return False, "**FAILED** \n" + \ 95 | str(e) + " \nsomething wrongings when trying to add TORRENT file" 96 | if os.path.exists(torrent_file_path): 97 | # Add Torrent Into Queue 98 | try: 99 | download = aria_instance.add_torrent( 100 | torrent_file_path, 101 | uris=None, 102 | options=None, 103 | position=None 104 | ) 105 | except Exception as e: 106 | return False, "**FAILED** \n" + \ 107 | str(e) + " \nPlease do not send SLOW links. Read /help" 108 | else: 109 | return True, "" + download.gid + "" 110 | else: 111 | return False, "**FAILED** \n" + \ 112 | str(e) + " \nPlease try other sources to get workable link" 113 | 114 | 115 | def add_url(aria_instance, text_url, c_file_name): 116 | options = None 117 | # if c_file_name is not None: 118 | # options = { 119 | # "dir": c_file_name 120 | # } 121 | uris = [text_url] 122 | # Add URL Into Queue 123 | try: 124 | download = aria_instance.add_uris( 125 | uris, 126 | options=options 127 | ) 128 | except Exception as e: 129 | return False, "**FAILED** \n" + \ 130 | str(e) + " \nPlease do not send SLOW links. Read /help" 131 | else: 132 | return True, "" + download.gid + "" 133 | 134 | 135 | async def call_apropriate_function( 136 | aria_instance, 137 | incoming_link, 138 | c_file_name, 139 | sent_message_to_update_tg_p, 140 | is_zip, 141 | cstom_file_name, 142 | is_unzip, 143 | is_unrar, 144 | is_untar, 145 | user_message 146 | ): 147 | if incoming_link.lower().startswith("magnet:"): 148 | sagtus, err_message = add_magnet( 149 | aria_instance, incoming_link, c_file_name) 150 | elif incoming_link.lower().endswith(".torrent"): 151 | sagtus, err_message = add_torrent(aria_instance, incoming_link) 152 | else: 153 | sagtus, err_message = add_url( 154 | aria_instance, incoming_link, c_file_name) 155 | if not sagtus: 156 | return sagtus, err_message 157 | LOGGER.info(err_message) 158 | # https://stackoverflow.com/a/58213653/4723940 159 | await check_progress_for_dl( 160 | aria_instance, 161 | err_message, 162 | sent_message_to_update_tg_p, 163 | None 164 | ) 165 | if incoming_link.startswith("magnet:"): 166 | # 167 | err_message = await check_metadata(aria_instance, err_message) 168 | # 169 | await asyncio.sleep(1) 170 | if err_message is not None: 171 | await check_progress_for_dl( 172 | aria_instance, 173 | err_message, 174 | sent_message_to_update_tg_p, 175 | None 176 | ) 177 | else: 178 | return False, "can't get metadata \n\n#stopped" 179 | await asyncio.sleep(1) 180 | file = aria_instance.get_download(err_message) 181 | to_upload_file = file.name 182 | # 183 | if is_zip: 184 | # first check if current free space allows this 185 | # ref: https://github.com/out386/aria-telegram-mirror-bot/blob/master/src/download_tools/aria-tools.ts#L194 186 | # archive the contents 187 | check_if_file = await create_archive(to_upload_file) 188 | if check_if_file is not None: 189 | to_upload_file = check_if_file 190 | # 191 | if is_unzip: 192 | check_ifi_file = await unzip_me(to_upload_file) 193 | if check_ifi_file is not None: 194 | to_upload_file = check_ifi_file 195 | # 196 | if is_unrar: 197 | check_ife_file = await unrar_me(to_upload_file) 198 | if check_ife_file is not None: 199 | to_upload_file = check_ife_file 200 | # 201 | if is_untar: 202 | check_ify_file = await untar_me(to_upload_file) 203 | if check_ify_file is not None: 204 | to_upload_file = check_ify_file 205 | # 206 | if to_upload_file: 207 | if CUSTOM_FILE_NAME: 208 | os.rename(to_upload_file, f"{CUSTOM_FILE_NAME}{to_upload_file}") 209 | to_upload_file = f"{CUSTOM_FILE_NAME}{to_upload_file}" 210 | else: 211 | to_upload_file = to_upload_file 212 | 213 | if cstom_file_name: 214 | os.rename(to_upload_file, cstom_file_name) 215 | to_upload_file = cstom_file_name 216 | else: 217 | to_upload_file = to_upload_file 218 | # 219 | response = {} 220 | LOGGER.info(response) 221 | user_id = user_message.from_user.id 222 | print(user_id) 223 | final_response = await upload_to_tg( 224 | sent_message_to_update_tg_p, 225 | to_upload_file, 226 | user_id, 227 | response 228 | ) 229 | LOGGER.info(final_response) 230 | try: 231 | message_to_send = "" 232 | for key_f_res_se in final_response: 233 | local_file_name = key_f_res_se 234 | message_id = final_response[key_f_res_se] 235 | channel_id = str(sent_message_to_update_tg_p.chat.id)[4:] 236 | private_link = f"https://t.me/c/{channel_id}/{message_id}" 237 | message_to_send += "👉 " 240 | message_to_send += local_file_name 241 | message_to_send += "" 242 | message_to_send += "\n" 243 | if message_to_send != "": 244 | mention_req_user = f"Your Requested Files\n\n" 245 | message_to_send = mention_req_user + message_to_send 246 | message_to_send = message_to_send + "\n\n" + "#uploads" 247 | else: 248 | message_to_send = "FAILED to upload files. 😞😞" 249 | await user_message.reply_text( 250 | text=message_to_send, 251 | quote=True, 252 | disable_web_page_preview=True 253 | ) 254 | except BaseException: 255 | pass 256 | return True, None 257 | # 258 | 259 | 260 | async def call_apropriate_function_g( 261 | aria_instance, 262 | incoming_link, 263 | c_file_name, 264 | sent_message_to_update_tg_p, 265 | is_zip, 266 | cstom_file_name, 267 | is_unzip, 268 | is_unrar, 269 | is_untar, 270 | user_message 271 | ): 272 | if incoming_link.lower().startswith("magnet:"): 273 | sagtus, err_message = add_magnet( 274 | aria_instance, incoming_link, c_file_name) 275 | elif incoming_link.lower().endswith(".torrent"): 276 | sagtus, err_message = add_torrent(aria_instance, incoming_link) 277 | else: 278 | sagtus, err_message = add_url( 279 | aria_instance, incoming_link, c_file_name) 280 | if not sagtus: 281 | return sagtus, err_message 282 | LOGGER.info(err_message) 283 | # https://stackoverflow.com/a/58213653/4723940 284 | await check_progress_for_dl( 285 | aria_instance, 286 | err_message, 287 | sent_message_to_update_tg_p, 288 | None 289 | ) 290 | if incoming_link.startswith("magnet:"): 291 | # 292 | err_message = await check_metadata(aria_instance, err_message) 293 | # 294 | await asyncio.sleep(1) 295 | if err_message is not None: 296 | await check_progress_for_dl( 297 | aria_instance, 298 | err_message, 299 | sent_message_to_update_tg_p, 300 | None 301 | ) 302 | else: 303 | return False, "can't get metadata \n\n#stopped" 304 | await asyncio.sleep(1) 305 | file = aria_instance.get_download(err_message) 306 | to_upload_file = file.name 307 | # 308 | if is_zip: 309 | # first check if current free space allows this 310 | # ref: https://github.com/out386/aria-telegram-mirror-bot/blob/master/src/download_tools/aria-tools.ts#L194 311 | # archive the contents 312 | check_if_file = await create_archive(to_upload_file) 313 | if check_if_file is not None: 314 | to_upload_file = check_if_file 315 | # 316 | if is_unzip: 317 | check_ifi_file = await unzip_me(to_upload_file) 318 | if check_ifi_file is not None: 319 | to_upload_file = check_ifi_file 320 | # 321 | if is_unrar: 322 | check_ife_file = await unrar_me(to_upload_file) 323 | if check_ife_file is not None: 324 | to_upload_file = check_ife_file 325 | # 326 | if is_untar: 327 | check_ify_file = await untar_me(to_upload_file) 328 | if check_ify_file is not None: 329 | to_upload_file = check_ify_file 330 | # 331 | if to_upload_file: 332 | if CUSTOM_FILE_NAME: 333 | os.rename(to_upload_file, f"{CUSTOM_FILE_NAME}{to_upload_file}") 334 | to_upload_file = f"{CUSTOM_FILE_NAME}{to_upload_file}" 335 | else: 336 | to_upload_file = to_upload_file 337 | 338 | if cstom_file_name: 339 | os.rename(to_upload_file, cstom_file_name) 340 | to_upload_file = cstom_file_name 341 | else: 342 | to_upload_file = to_upload_file 343 | # 344 | response = {} 345 | LOGGER.info(response) 346 | user_id = user_message.from_user.id 347 | print(user_id) 348 | final_response = await upload_to_gdrive( 349 | to_upload_file, 350 | sent_message_to_update_tg_p, 351 | user_message, 352 | user_id 353 | ) 354 | # 355 | 356 | 357 | async def call_apropriate_function_t( 358 | to_upload_file_g, 359 | sent_message_to_update_tg_p, 360 | is_unzip, 361 | is_unrar, 362 | is_untar 363 | ): 364 | # 365 | to_upload_file = to_upload_file_g 366 | if is_unzip: 367 | check_ifi_file = await unzip_me(to_upload_file_g) 368 | if check_ifi_file is not None: 369 | to_upload_file = check_ifi_file 370 | # 371 | if is_unrar: 372 | check_ife_file = await unrar_me(to_upload_file_g) 373 | if check_ife_file is not None: 374 | to_upload_file = check_ife_file 375 | # 376 | if is_untar: 377 | check_ify_file = await untar_me(to_upload_file_g) 378 | if check_ify_file is not None: 379 | to_upload_file = check_ify_file 380 | # 381 | response = {} 382 | LOGGER.info(response) 383 | sent_message_to_update_tg_p.reply_to_message.from_user.id 384 | final_response = await upload_to_gdrive( 385 | to_upload_file, 386 | sent_message_to_update_tg_p 387 | ) 388 | LOGGER.info(final_response) 389 | # if to_upload_file: 390 | # if CUSTOM_FILE_NAME: 391 | #os.rename(to_upload_file, f"{CUSTOM_FILE_NAME}{to_upload_file}") 392 | #to_upload_file = f"{CUSTOM_FILE_NAME}{to_upload_file}" 393 | # else: 394 | #to_upload_file = to_upload_file 395 | 396 | # if cstom_file_name: 397 | #os.rename(to_upload_file, cstom_file_name) 398 | #to_upload_file = cstom_file_name 399 | # else: 400 | #to_upload_file = to_upload_file 401 | ''' 402 | 403 | LOGGER.info(final_response) 404 | message_to_send = "" 405 | for key_f_res_se in final_response: 406 | local_file_name = key_f_res_se 407 | message_id = final_response[key_f_res_se] 408 | channel_id = str(AUTH_CHANNEL)[4:] 409 | private_link = f"https://t.me/c/{channel_id}/{message_id}" 410 | message_to_send += "👉 " 413 | message_to_send += local_file_name 414 | message_to_send += "" 415 | message_to_send += "\n" 416 | if message_to_send != "": 417 | mention_req_user = f"Your Requested Files\n\n" 418 | message_to_send = mention_req_user + message_to_send 419 | message_to_send = message_to_send + "\n\n" + "#uploads" 420 | else: 421 | message_to_send = "FAILED to upload files. 😞😞" 422 | await sent_message_to_update_tg_p.reply_to_message.reply_text( 423 | text=message_to_send, 424 | quote=True, 425 | disable_web_page_preview=True 426 | ) 427 | return True, None 428 | ''' 429 | 430 | 431 | # https://github.com/jaskaranSM/UniBorg/blob/6d35cf452bce1204613929d4da7530058785b6b1/stdplugins/aria.py#L136-L164 432 | async def check_progress_for_dl(aria2, gid, event, previous_message): 433 | try: 434 | file = aria2.get_download(gid) 435 | complete = file.is_complete 436 | is_file = file.seeder 437 | if not complete: 438 | if not file.error_message: 439 | msg = "" 440 | # sometimes, this weird https://t.me/c/1220993104/392975 441 | # error creeps up 442 | # TODO: temporary workaround 443 | downloading_dir_name = "N/A" 444 | try: 445 | # another derp -_- 446 | # https://t.me/c/1220993104/423318 447 | downloading_dir_name = str(file.name) 448 | except BaseException: 449 | pass 450 | # 451 | msg = f"\n`{downloading_dir_name}` - Downloading" 452 | msg += f"\nSize: {file.total_length_string()}" 453 | msg += f"\nProgress: {file.progress_string()} at {file.download_speed_string()}" 454 | 455 | if is_file is None: 456 | msg += f"\nETA: {file.eta_string()} | P : {file.connections}" 457 | else: 458 | msg += f"\nETA: {file.eta_string()} | P : {file.connections} | S : {file.num_seeders}" 459 | 460 | # msg += f"\nStatus: {file.status}" 461 | msg += f"\nETA: {file.eta_string()}" 462 | inline_keyboard = [] 463 | ikeyboard = [] 464 | ikeyboard.append( 465 | InlineKeyboardButton( 466 | "Cancel 🚫", 467 | callback_data=(f"cancel {gid}").encode("UTF-8"))) 468 | inline_keyboard.append(ikeyboard) 469 | reply_markup = InlineKeyboardMarkup(inline_keyboard) 470 | #msg += reply_markup 471 | LOGGER.info(msg) 472 | if msg != previous_message: 473 | await event.edit(msg, reply_markup=reply_markup) 474 | previous_message = msg 475 | else: 476 | msg = file.error_message 477 | await asyncio.sleep(5) 478 | await event.edit(f"`{msg}`") 479 | return False 480 | await asyncio.sleep(5) 481 | await check_progress_for_dl(aria2, gid, event, previous_message) 482 | else: 483 | await asyncio.sleep(5) 484 | await event.edit(f"File Downloaded Successfully: `{file.name}`") 485 | return True 486 | except Exception as e: 487 | LOGGER.info(str(e)) 488 | if " not found" in str(e) or "'file'" in str(e): 489 | await event.edit("Download Canceled") 490 | return False 491 | elif " depth exceeded" in str(e): 492 | file.remove(force=True) 493 | await event.edit("Download Auto Canceled\nYour Torrent/Link is Dead.") 494 | return False 495 | else: 496 | LOGGER.info(str(e)) 497 | await event.edit("error :\n`{}` \n\n#error".format(str(e))) 498 | return 499 | # https://github.com/jaskaranSM/UniBorg/blob/6d35cf452bce1204613929d4da7530058785b6b1/stdplugins/aria.py#L136-L164 500 | 501 | 502 | async def check_metadata(aria2, gid): 503 | file = aria2.get_download(gid) 504 | LOGGER.info(file) 505 | if not file.followed_by_ids: 506 | # https://t.me/c/1213160642/496 507 | return None 508 | new_gid = file.followed_by_ids[0] 509 | LOGGER.info("Changing GID " + gid + " to " + new_gid) 510 | return new_gid 511 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . --------------------------------------------------------------------------------