├── runtime.txt ├── _config.yml ├── rclone.jpg ├── heroku.yml ├── requirements.txt ├── tobrot ├── helper_funcs │ ├── exceptions.py │ ├── copy_similar_file.py │ ├── magnetic_link_regex.py │ ├── admin_check.py │ ├── real_debrid_extractor.py │ ├── download_from_link.py │ ├── help_Nekmo_ffmpeg.py │ ├── ytplaylist.py │ ├── download.py │ ├── extract_link_from_message.py │ ├── display_progress.py │ ├── split_large_files.py │ ├── create_compressed_archive.py │ ├── direct_link_generator.py │ ├── cloneHelper.py │ ├── youtube_dl_button.py │ ├── youtube_dl_extractor.py │ ├── download_aria_p_n.py │ └── upload_to_tg.py ├── UserDynaConfig.py ├── aria2 │ └── aria2.conf ├── plugins │ ├── rclone_size.py │ ├── custom_thumbnail.py │ ├── choose_rclone_config.py │ ├── new_join_fn.py │ ├── call_back_button_handler.py │ ├── status_message_fn.py │ └── incoming_message_fn.py ├── __init__.py └── __main__.py ├── .github └── workflows │ └── main.yml ├── Dockerfile ├── start.sh ├── sample_config.env ├── extract ├── .gitignore ├── app.json ├── README.md └── COPYING /runtime.txt: -------------------------------------------------------------------------------- 1 | python-3.9.2 2 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /rclone.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MaxxRider/Leech-Pro/HEAD/rclone.jpg -------------------------------------------------------------------------------- /heroku.yml: -------------------------------------------------------------------------------- 1 | build: 2 | docker: 3 | worker: Dockerfile 4 | run: 5 | worker: bash start.sh 6 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp 2 | aria2p==0.9.1 3 | hachoir 4 | Pillow 5 | pyrogram==1.3.0 6 | tgcrypto 7 | yt_dlp 8 | hurry.filesize 9 | python-dotenv 10 | psutil 11 | pyprog 12 | beautifulsoup4 13 | bs4 14 | lxml 15 | requests 16 | messages 17 | js2py 18 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/exceptions.py: -------------------------------------------------------------------------------- 1 | class DirectDownloadLinkException(Exception): 2 | """No method found for extracting direct download link from the http link""" 3 | pass 4 | 5 | 6 | class NotSupportedExtractionArchive(Exception): 7 | """The archive format use is trying to extract is not supported""" 8 | pass -------------------------------------------------------------------------------- /tobrot/helper_funcs/copy_similar_file.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | import logging 6 | import os 7 | import time 8 | from shutil import copyfile 9 | 10 | 11 | async def copy_file(input_file, output_dir): 12 | output_file = os.path.join(output_dir, str(time.time()) + ".jpg") 13 | # https://stackoverflow.com/a/123212/4723940 14 | copyfile(input_file, output_file) 15 | return output_file -------------------------------------------------------------------------------- /tobrot/helper_funcs/magnetic_link_regex.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | import logging 6 | import os 7 | import re 8 | 9 | 10 | MAGNETIC_LINK_REGEX = r"magnet\:\?xt\=urn\:btih\:([A-F\d]+)" 11 | 12 | 13 | def extract_info_hash_from_ml(magnetic_link): 14 | ml_re_match = re.search(MAGNETIC_LINK_REGEX, magnetic_link) 15 | if ml_re_match is not None: 16 | return ml_re_match.group(1) 17 | -------------------------------------------------------------------------------- /tobrot/UserDynaConfig.py: -------------------------------------------------------------------------------- 1 | class UserDynaConfig: 2 | 3 | def __init__(self, user_id, upload_as_doc=False): 4 | self.user_id = user_id 5 | self.upload_as_doc = upload_as_doc 6 | 7 | def __hash__(self): 8 | return hash((self.user_id, self.upload_as_doc)) 9 | 10 | def __eq__(self, other): 11 | if not isinstance(other, type(self)): 12 | return NotImplemented 13 | return self.user_id == other.user_id 14 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/admin_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | from tobrot import AUTH_CHANNEL 4 | 5 | 6 | async def AdminCheck(client, chat_id, user_id): 7 | chat = await client.get_chat(chat_id) 8 | if chat.type == "private" and chat_id in AUTH_CHANNEL: 9 | return True 10 | SELF = await client.get_chat_member(chat_id=chat_id, user_id=user_id) 11 | admin_strings = ["creator", "administrator"] 12 | # https://git.colinshark.de/PyroBot/PyroBot/src/branch/master/pyrobot/modules/admin.py#L69 13 | if SELF.status not in admin_strings: 14 | return False 15 | else: 16 | return True -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | # This is a workflow to deploy a leech bot to heroku using GitHub Actions 2 | 3 | name: Deploy To Heroku 4 | 5 | on: workflow_dispatch 6 | 7 | jobs: 8 | deploy: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v2 12 | - uses: akhileshns/heroku-deploy@v3.12.12 13 | with: 14 | heroku_api_key: ${{secrets.HEROKU_API_KEY}} 15 | heroku_app_name: ${{secrets.HEROKU_APP_NAME}} 16 | heroku_email: ${{secrets.HEROKU_EMAIL}} 17 | usedocker: true 18 | docker_heroku_process_type: worker 19 | stack: "container" 20 | region: "eu" 21 | env: 22 | HD_CONFIG_ENV_URL: ${{secrets.CONFIG_ENV_URL}} 23 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:20.04 2 | 3 | 4 | RUN mkdir ./app 5 | RUN chmod 777 ./app 6 | WORKDIR /app 7 | 8 | ENV DEBIAN_FRONTEND=noninteractive 9 | ENV TZ=Asia/Kolkata 10 | 11 | RUN apt -qq update --fix-missing && \ 12 | apt -qq install -y git \ 13 | aria2 \ 14 | wget \ 15 | curl \ 16 | busybox \ 17 | unzip \ 18 | unrar \ 19 | tar \ 20 | python3 \ 21 | ffmpeg \ 22 | python3-pip \ 23 | p7zip-full \ 24 | p7zip-rar 25 | 26 | RUN wget https://rclone.org/install.sh 27 | RUN bash install.sh 28 | 29 | RUN mkdir /app/gautam 30 | RUN wget -O /app/gautam/gclone.gz https://git.io/JJMSG 31 | RUN gzip -d /app/gautam/gclone.gz 32 | RUN chmod 0775 /app/gautam/gclone 33 | 34 | COPY requirements.txt . 35 | RUN pip3 install --no-cache-dir -r requirements.txt 36 | COPY . . 37 | RUN chmod +x extract 38 | CMD ["bash","start.sh"] 39 | -------------------------------------------------------------------------------- /tobrot/aria2/aria2.conf: -------------------------------------------------------------------------------- 1 | check-certificate=false 2 | bt-max-peers=0 3 | bt-tracker-connect-timeout=300 4 | bt-stop-timeout=300 5 | seed-time=0.01 6 | min-split-size=10M 7 | follow-torrent=mem 8 | split=10 9 | daemon=true 10 | allow-overwrite=true 11 | max-overall-download-limit=0 12 | max-overall-upload-limit=1K 13 | peer-id-prefix=-qB4350- 14 | user-agent=qBittorrent/4.3.5 15 | peer-agent=qBittorrent/4.3.5 16 | disk-cache=64M 17 | file-allocation=prealloc 18 | continue=true 19 | auto-file-renaming=true 20 | bt-enable-lpd=true 21 | seed-time=0.01 22 | seed-ratio=1.0 23 | file-allocation=prealloc 24 | max-file-not-found=20 25 | max-tries=20 26 | retry-wait=3 27 | auto-file-renaming=true 28 | reuse-uri=true 29 | http-accept-gzip=true 30 | listen-port=49152-65535 31 | content-disposition-default-utf8=true 32 | bt-tracker-connect-timeout=300 33 | dht-listen-port=51513 34 | enable-dht=true 35 | enable-dht6=true 36 | dht-file-path=/app/dht.dat 37 | dht-file-path6=/app/dht6.dat 38 | dht-entry-point=dht.transmissionbt.com:6881 39 | dht-entry-point6=dht.transmissionbt.com:6881 -------------------------------------------------------------------------------- /tobrot/helper_funcs/real_debrid_extractor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | 9 | import aiohttp 10 | from tobrot import REAL_DEBRID_KEY, LOGGER 11 | 12 | 13 | BASE_URL = "https://api.real-debrid.com/rest/1.0" 14 | 15 | 16 | async def fetch(session, url, data): 17 | async with session.post(url, data=data) as response: 18 | return await response.json() 19 | 20 | 21 | async def extract_it(restricted_link, custom_file_name): 22 | async with aiohttp.ClientSession() as session: 23 | url_to_send = BASE_URL + "/unrestrict/link?auth_token=" + REAL_DEBRID_KEY 24 | to_send_data = {"link": restricted_link} 25 | html = await fetch(session, url_to_send, to_send_data) 26 | LOGGER.info(html) 27 | downloadable_url = html.get("download") 28 | original_file_name = custom_file_name 29 | if original_file_name is None: 30 | original_file_name = html.get("filename") 31 | return downloadable_url, original_file_name 32 | -------------------------------------------------------------------------------- /start.sh: -------------------------------------------------------------------------------- 1 | #bin #!bash 2 | 3 | ###### Adding Files ###### 4 | wget -O /app/tobrot/aria2/dht.dat https://github.com/P3TERX/aria2.conf/raw/master/dht.dat 5 | wget -O /app/tobrot/aria2/dht6.dat https://github.com/P3TERX/aria2.conf/raw/master/dht6.dat 6 | TRACKER=`curl -Ns https://raw.githubusercontent.com/XIU2/TrackersListCollection/master/all.txt -: https://ngosang.github.io/trackerslist/trackers_all_http.txt -: https://newtrackon.com/api/all -: https://raw.githubusercontent.com/DeSireFire/animeTrackerList/master/AT_all.txt -: https://torrends.to/torrent-tracker-list/?download=latest | awk '$1' | tr '\n' ',' | cat` 7 | ran=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 12 | head -n 1) 8 | ###### Done Addding Files ###### 9 | 10 | 11 | if [[ -n $RCLONE_CONFIG_URL ]]; then 12 | echo "Rclone config detected 📁📁" 13 | wget -q $RCLONE_CONFIG_URL -O /app/rclone.conf 14 | fi 15 | 16 | if [[ -n $CONFIG_ENV_URL ]]; then 17 | echo " Found config.env File 📁📁 " 18 | wget -q $CONFIG_ENV_URL -O /app/config.env 19 | fi 20 | 21 | 22 | 23 | echo "Starting Your Bot... 👾👾" 24 | python3 -m tobrot 25 | 26 | -------------------------------------------------------------------------------- /sample_config.env: -------------------------------------------------------------------------------- 1 | # READ README.md BEFORE DOING THIS 2 | 3 | 4 | #________COMPULSORY____________# 5 | 6 | TG_BOT_TOKEN = "" # ENTER BOT TOKEN (Get your BOT_TOKEN by talking to @botfather) 7 | APP_ID = 8 | API_HASH = "" 9 | OWNER_ID = 10 | AUTH_CHANNEL = "" #Add IDs separated by a SPACE (Like :: -10012503747 -10012586941 539295917) 11 | 12 | 13 | #________NOT COMPULSORY____________# 14 | 15 | # For RCLONE :: 16 | # Name of the folder....not ID 17 | DESTINATION_FOLDER = "TorrentLeech-Gdrive" 18 | INDEX_LINK = "" 19 | 20 | # OTHERS :: 21 | DEF_THUMB_NAIL_VID_S = "" 22 | ARIA_TWO_STARTED_PORT = "6800" 23 | EDIT_SLEEP_TIME_OUT = "15" 24 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START = 600 25 | MAX_TG_SPLIT_FILE_SIZE = "2097152000" 26 | 27 | FINISHED_PROGRESS_STR = "" 28 | UN_FINISHED_PROGRESS_STR = "" 29 | 30 | CUSTOM_FILE_NAME = "" 31 | 32 | UPLOAD_AS_DOC = "" 33 | 34 | # Commands Customization (Completely Optional) 35 | # If you want to change 36 | LEECH_COMMAND = "" 37 | YTDL_COMMAND = "" 38 | GYTDL_COMMAND = "" 39 | GLEECH_COMMAND = "" 40 | TELEGRAM_LEECH_COMMAND = "" 41 | TELEGRAM_LEECH_UNZIP_COMMAND = "" 42 | PYTDL_COMMAND = "" 43 | CLONE_COMMAND_G = "" 44 | UPLOAD_COMMAND = "" 45 | RENEWME_COMMAND = "" 46 | SAVE_THUMBNAIL = "" 47 | CLEAR_THUMBNAIL = "" 48 | GET_SIZE_G = "" 49 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/download_from_link.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | MaxxRider 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import time 9 | 10 | from tobrot import DOWNLOAD_LOCATION, LOGGER 11 | 12 | 13 | async def request_download(url, file_name, r_user_id): 14 | directory_path = os.path.join(DOWNLOAD_LOCATION, str(r_user_id), str(time.time())) 15 | # create download directory, if not exist 16 | if not os.path.isdir(directory_path): 17 | os.makedirs(directory_path) 18 | local_file_path = os.path.join(directory_path, file_name) 19 | command_to_exec = ["wget", "-O", local_file_path, url] 20 | process = await asyncio.create_subprocess_exec( 21 | *command_to_exec, 22 | # stdout must a pipe to be accessible as process.stdout 23 | stdout=asyncio.subprocess.PIPE, 24 | stderr=asyncio.subprocess.PIPE, 25 | ) 26 | # Wait for the subprocess to finish 27 | stdout, stderr = await process.communicate() 28 | e_response = stderr.decode().strip() 29 | # logger.info(e_response) 30 | t_response = stdout.decode().strip() 31 | # logger.info(t_response) 32 | final_m_r = e_response + "\n\n\n" + t_response 33 | if os.path.exists(local_file_path): 34 | return True, local_file_path 35 | else: 36 | return False, final_m_r 37 | -------------------------------------------------------------------------------- /extract: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # property of python-aria-mirror-bot 3 | 4 | if [ $# -lt 1 ]; then 5 | echo "Usage: $(basename $0) FILES" 6 | exit 1 7 | fi 8 | 9 | extract() { 10 | arg="$1" 11 | cd "$(dirname "$arg")" || exit 12 | case "$arg" in 13 | *.tar.bz2) 14 | tar xjf "$arg" --one-top-level 15 | local code=$? 16 | ;; 17 | *.tar.gz) 18 | tar xzf "$arg" --one-top-level 19 | local code=$? 20 | ;; 21 | *.bz2) 22 | bunzip2 "$arg" 23 | local code=$? 24 | ;; 25 | *.gz) 26 | gunzip "$arg" 27 | local code=$? 28 | ;; 29 | *.tar) 30 | tar xf "$arg" --one-top-level 31 | local code=$? 32 | ;; 33 | *.tbz2) 34 | (tar xjf "$arg" --one-top-level) 35 | local code=$? 36 | ;; 37 | *.tgz) 38 | tar xzf "$arg" --one-top-level 39 | local code=$? 40 | ;; 41 | *.zip) 42 | a_dir=$(expr "$arg" : '\(.*\).zip') 43 | unzip "$arg" -d "$a_dir" 44 | local code=$? 45 | ;; 46 | *.7z) 47 | a_dir=$(expr "$arg" : '\(.*\).7z') 48 | 7z x "$arg" -o"$a_dir" 49 | local code=$? 50 | ;; 51 | *.Z) 52 | uncompress "$arg" 53 | local code=$? 54 | ;; 55 | *.rar) 56 | a_dir=$(expr "$arg" : '\(.*\).rar') 57 | mkdir "$a_dir" 58 | 7z x "$arg" -o"$a_dir" 59 | local code=$? 60 | ;; 61 | *) 62 | echo "'$arg' cannot be extracted via extract()" 1>&2 63 | exit 1 64 | ;; 65 | esac 66 | cd - || exit $? 67 | exit $code 68 | } 69 | 70 | extract "$1" 71 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/help_Nekmo_ffmpeg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import time 9 | 10 | from tobrot.helper_funcs.copy_similar_file import copy_file 11 | from tobrot import LOGGER 12 | 13 | 14 | async def take_screen_shot(video_file, output_directory, ttl): 15 | # https://stackoverflow.com/a/13891070/4723940 16 | out_put_file_name = os.path.join(output_directory, str(time.time()) + ".jpg") 17 | if video_file.upper().endswith(("MKV", "MP4", "WEBM", "AVI", "MOV", "OGG", "WMV", "M4V", "TS", "MPG", "MTS", "M2TS", "3GP")): 18 | file_genertor_command = [ 19 | "ffmpeg", 20 | "-ss", 21 | str(ttl), 22 | "-i", 23 | video_file, 24 | "-vframes", 25 | "1", 26 | out_put_file_name, 27 | ] 28 | # width = "90" 29 | process = await asyncio.create_subprocess_exec( 30 | *file_genertor_command, 31 | # stdout must a pipe to be accessible as process.stdout 32 | stdout=asyncio.subprocess.PIPE, 33 | stderr=asyncio.subprocess.PIPE, 34 | ) 35 | # Wait for the subprocess to finish 36 | stdout, stderr = await process.communicate() 37 | e_response = stderr.decode().strip() 38 | t_response = stdout.decode().strip() 39 | # 40 | if os.path.lexists(out_put_file_name): 41 | return out_put_file_name 42 | else: 43 | return None -------------------------------------------------------------------------------- /tobrot/helper_funcs/ytplaylist.py: -------------------------------------------------------------------------------- 1 | # (c) gautamajay52 | MaxxRider 2 | # 3 | 4 | 5 | import asyncio 6 | import os 7 | import shutil 8 | import subprocess 9 | 10 | import requests 11 | from tobrot import DOWNLOAD_LOCATION, LOGGER 12 | from tobrot.helper_funcs.upload_to_tg import upload_to_gdrive, upload_to_tg 13 | 14 | 15 | async def yt_playlist_downg(message, i_m_sefg, client, G_DRIVE): 16 | url = None 17 | if message.reply_to_message: 18 | url = message.reply_to_message.text 19 | else: 20 | url = message.text.split()[1] 21 | usr = message.message_id 22 | messa_ge = i_m_sefg.reply_to_message 23 | fol_der = f"{usr}youtube" 24 | try: 25 | os.mkdir(fol_der) 26 | except: 27 | pass 28 | cmd = [ 29 | "yt-dlp", 30 | "-i", 31 | "-f", 32 | "bestvideo[ext=mp4]+bestaudio[ext=m4a]/mp4", 33 | "-o", 34 | f"{fol_der}/%(playlist)s/%(playlist_index)s - %(title)s.%(ext)s", 35 | f"{url}", 36 | ] 37 | gau_tam = await asyncio.create_subprocess_exec( 38 | *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 39 | ) 40 | gau, tam = await gau_tam.communicate() 41 | LOGGER.info(gau.decode("utf-8")) 42 | LOGGER.info(tam.decode("utf-8")) 43 | e_response = tam.decode().strip() 44 | 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." 45 | if e_response and ad_string_to_replace in e_response: 46 | error_message = e_response.replace(ad_string_to_replace, "") 47 | await i_m_sefg.edit_text(error_message) 48 | return False, None 49 | if G_DRIVE: 50 | get_g = os.listdir(fol_der) 51 | for ga_u in get_g: 52 | ta_m = os.path.join(fol_der, ga_u) 53 | await upload_to_gdrive(ta_m, i_m_sefg, message, usr) 54 | else: 55 | final_response = await upload_to_tg(i_m_sefg, fol_der, usr, {}, client) 56 | try: 57 | shutil.rmtree(fol_der) 58 | except: 59 | pass 60 | -------------------------------------------------------------------------------- /tobrot/plugins/rclone_size.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) gautamajay52 4 | import asyncio 5 | import logging 6 | import os 7 | import re 8 | import subprocess 9 | 10 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup 11 | from tobrot import DESTINATION_FOLDER, EDIT_SLEEP_TIME_OUT, LOGGER, RCLONE_CONFIG 12 | 13 | 14 | async def check_size_g(client, message): 15 | # await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 16 | del_it = await message.reply_text("🔊 Checking size...wait!!!") 17 | if not os.path.exists("rclone.conf"): 18 | with open("rclone.conf", "w+", newline="\n", encoding="utf-8") as fole: 19 | fole.write(f"{RCLONE_CONFIG}") 20 | if os.path.exists("rclone.conf"): 21 | with open("rclone.conf", "r+") as file: 22 | con = file.read() 23 | gUP = re.findall("\[(.*)\]", con)[0] 24 | LOGGER.info(gUP) 25 | destination = f"{DESTINATION_FOLDER}" 26 | cmd = ["rclone", "size", "--config=./rclone.conf", f"{gUP}:{destination}"] 27 | gau_tam = await asyncio.create_subprocess_exec( 28 | *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 29 | ) 30 | gau, tam = await gau_tam.communicate() 31 | LOGGER.info(gau) 32 | LOGGER.info(tam) 33 | LOGGER.info(tam.decode("utf-8")) 34 | gautam = gau.decode("utf-8") 35 | LOGGER.info(gautam) 36 | await asyncio.sleep(5) 37 | await message.reply_text(f"🔊CloudInfo:\n\n{gautam}") 38 | await del_it.delete() 39 | 40 | 41 | # gautamajay52 42 | 43 | 44 | async def g_clearme(client, message): 45 | inline_keyboard = [] 46 | ikeyboard = [] 47 | ikeyboard.append( 48 | InlineKeyboardButton("Yes 🚫", callback_data=("fuckingdo").encode("UTF-8")) 49 | ) 50 | ikeyboard.append( 51 | InlineKeyboardButton("No 🤗", callback_data=("fuckoff").encode("UTF-8")) 52 | ) 53 | inline_keyboard.append(ikeyboard) 54 | reply_markup = InlineKeyboardMarkup(inline_keyboard) 55 | await message.reply_text( 56 | "Are you sure? 🚫 This will delete all your downloads locally 🚫", 57 | reply_markup=reply_markup, 58 | quote=True, 59 | ) 60 | -------------------------------------------------------------------------------- /tobrot/plugins/custom_thumbnail.py: -------------------------------------------------------------------------------- 1 | """ThumbNail utilities, © @AnyDLBot""" 2 | 3 | 4 | import os 5 | 6 | from hachoir.metadata import extractMetadata 7 | from hachoir.parser import createParser 8 | from PIL import Image 9 | from tobrot import DOWNLOAD_LOCATION 10 | 11 | 12 | async def save_thumb_nail(client, message): 13 | thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails") 14 | thumb_image_path = os.path.join( 15 | thumbnail_location, str(message.from_user.id) + ".jpg" 16 | ) 17 | ismgs = await message.reply_text("processing ...") 18 | if message.reply_to_message is not None: 19 | if not os.path.isdir(thumbnail_location): 20 | os.makedirs(thumbnail_location) 21 | download_location = thumbnail_location + "/" 22 | downloaded_file_name = await client.download_media( 23 | message=message.reply_to_message, file_name=download_location 24 | ) 25 | # https://stackoverflow.com/a/21669827/4723940 26 | Image.open(downloaded_file_name).convert("RGB").save(downloaded_file_name) 27 | metadata = extractMetadata(createParser(downloaded_file_name)) 28 | height = 0 29 | if metadata.has("height"): 30 | height = metadata.get("height") 31 | # resize image 32 | # ref: https://t.me/PyrogramChat/44663 33 | img = Image.open(downloaded_file_name) 34 | # https://stackoverflow.com/a/37631799/4723940 35 | # img.thumbnail((320, 320)) 36 | img.resize((320, height)) 37 | img.save(thumb_image_path, "JPEG") 38 | # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails 39 | os.remove(downloaded_file_name) 40 | await ismgs.edit( 41 | "✅ Custom video / file thumbnail saved. " 42 | + "This image will be used in the upload, till /clearthumbnail." 43 | ) 44 | else: 45 | await ismgs.edit("❌ Reply to a photo to save custom thumbnail") 46 | 47 | 48 | async def clear_thumb_nail(client, message): 49 | thumbnail_location = os.path.join(DOWNLOAD_LOCATION, "thumbnails") 50 | thumb_image_path = os.path.join( 51 | thumbnail_location, str(message.from_user.id) + ".jpg" 52 | ) 53 | ismgs = await message.reply_text("processing ...") 54 | if os.path.exists(thumb_image_path): 55 | os.remove(thumb_image_path) 56 | await ismgs.edit("✅ Custom thumbnail cleared successfully.") 57 | else: 58 | await ismgs.edit("❌ Nothing to clear.") -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | config.env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /tobrot/plugins/choose_rclone_config.py: -------------------------------------------------------------------------------- 1 | # This is code to switch which rclone config section to use. This setting affects the entire bot(And at this time, the cloneHelper only support gdrive, so you should only choose to use gdrive config section) 2 | #!/usr/bin/env python3 3 | # -*- coding: utf-8 -*- 4 | # (c) xiaoqi-beta | gautamajay52 5 | 6 | import logging 7 | import os 8 | import re 9 | from configparser import ConfigParser 10 | 11 | import pyrogram.types as pyrogram 12 | from pyrogram.types import CallbackQuery 13 | from tobrot import LOGGER, OWNER_ID 14 | 15 | 16 | async def rclone_command_f(client, message): 17 | """/rclone command""" 18 | LOGGER.info( 19 | f"rclone command from chatid:{message.chat.id}, userid:{message.from_user.id}" 20 | ) 21 | if message.from_user.id == OWNER_ID and message.chat.type == "private": 22 | config = ConfigParser() 23 | config.read("rclone_bak.conf") 24 | sections = list(config.sections()) 25 | inline_keyboard = [] 26 | for section in sections: 27 | ikeyboard = [ 28 | pyrogram.InlineKeyboardButton( 29 | section, callback_data=(f"rclone_{section}").encode("UTF-8") 30 | ) 31 | ] 32 | inline_keyboard.append(ikeyboard) 33 | config = ConfigParser() 34 | config.read("rclone.conf") 35 | section = config.sections()[0] 36 | msg_text = f"""Default section of rclone config is: **{section}**\n\n 37 | There are {len(sections)} sections in your rclone.conf file, 38 | please choose which section you want to use:""" 39 | ikeyboard = [ 40 | pyrogram.InlineKeyboardButton( 41 | "‼️ Cancel ‼️", callback_data=(f"rcloneCancel").encode("UTF-8") 42 | ) 43 | ] 44 | inline_keyboard.append(ikeyboard) 45 | reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard) 46 | await message.reply_text(text=msg_text, reply_markup=reply_markup) 47 | else: 48 | await message.reply_text("You have no permission!") 49 | LOGGER.warning( 50 | f"uid={message.from_user.id} have no permission to edit rclone config!" 51 | ) 52 | 53 | 54 | async def rclone_button_callback(bot, update: CallbackQuery): 55 | """rclone button callback""" 56 | if update.data == "rcloneCancel": 57 | config = ConfigParser() 58 | config.read("rclone.conf") 59 | section = config.sections()[0] 60 | await update.message.edit_text( 61 | f"Opration canceled! \n\nThe default section of rclone config is: **{section}**" 62 | ) 63 | LOGGER.info( 64 | f"Opration canceled! The default section of rclone config is: {section}" 65 | ) 66 | else: 67 | section = update.data.split("_", maxsplit=1)[1] 68 | with open("rclone.conf", "w", newline="\n", encoding="utf-8") as f: 69 | config = ConfigParser() 70 | config.read("rclone_bak.conf") 71 | temp = ConfigParser() 72 | temp[section] = config[section] 73 | temp.write(f) 74 | await update.message.edit_text( 75 | f"Default rclone config changed to **{section}**" 76 | ) 77 | LOGGER.info(f"Default rclone config changed to {section}") -------------------------------------------------------------------------------- /tobrot/helper_funcs/download.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) gautamajay52 | Shrimadhav U K 4 | 5 | import asyncio 6 | import logging 7 | import math 8 | import os 9 | import re 10 | import subprocess 11 | import time 12 | from datetime import datetime 13 | from pathlib import Path 14 | 15 | from pyrogram import Client, filters 16 | from tobrot import DOWNLOAD_LOCATION, LOGGER, TELEGRAM_LEECH_UNZIP_COMMAND 17 | from tobrot.helper_funcs.create_compressed_archive import unzip_me, get_base_name 18 | from tobrot.helper_funcs.display_progress import Progress 19 | from tobrot.helper_funcs.upload_to_tg import upload_to_gdrive 20 | 21 | 22 | async def down_load_media_f(client, message): # to be removed 23 | user_command = message.command[0] 24 | user_id = message.from_user.id 25 | 26 | if message.reply_to_message is not None: 27 | the_real_download_location, mess_age = await download_tg(client, message) 28 | the_real_download_location_g = the_real_download_location 29 | if user_command == TELEGRAM_LEECH_UNZIP_COMMAND.lower(): 30 | try: 31 | check_ifi_file = get_base_name(the_real_download_location) 32 | file_up = await unzip_me(the_real_download_location) 33 | if os.path.exists(check_ifi_file): 34 | the_real_download_location_g = file_up 35 | except Exception as ge: 36 | LOGGER.info(ge) 37 | LOGGER.info( 38 | f"Can't extract {os.path.basename(the_real_download_location)}, Uploading the same file" 39 | ) 40 | await upload_to_gdrive(the_real_download_location_g, mess_age, message, user_id) 41 | else: 42 | await mess_age.edit_text( 43 | "Reply to a Telegram Media, to upload to the Cloud Drive." 44 | ) 45 | 46 | 47 | async def download_tg(client, message): 48 | user_id = message.from_user.id 49 | LOGGER.info(user_id) 50 | mess_age = await message.reply_text("**DownloadinG...**", quote=True) 51 | if not os.path.isdir(DOWNLOAD_LOCATION): 52 | os.makedirs(DOWNLOAD_LOCATION) 53 | rep_mess = message.reply_to_message 54 | if rep_mess is not None: 55 | file = [rep_mess.document, rep_mess.video, rep_mess.audio] 56 | file_name = [fi for fi in file if fi is not None][0].file_name 57 | start_t = datetime.now() 58 | download_location = str(Path("./").resolve()) + "/" 59 | c_time = time.time() 60 | prog = Progress(user_id, client, mess_age) 61 | try: 62 | the_real_download_location = await client.download_media( 63 | message=message.reply_to_message, 64 | file_name=download_location, 65 | progress=prog.progress_for_pyrogram, 66 | progress_args=(f"**• Downloading :** `{file_name}`", c_time) 67 | ) 68 | except Exception as g_e: 69 | await mess_age.edit(str(g_e)) 70 | LOGGER.error(g_e) 71 | return 72 | end_t = datetime.now() 73 | ms = (end_t - start_t).seconds 74 | LOGGER.info(the_real_download_location) 75 | await asyncio.sleep(2) 76 | if the_real_download_location: 77 | await mess_age.edit_text( 78 | f"Downloaded to {the_real_download_location} in {ms} seconds" 79 | ) 80 | else: 81 | await mess_age.edit_text("😔 Download Cancelled or some error happened") 82 | return None, mess_age 83 | return the_real_download_location, mess_age -------------------------------------------------------------------------------- /tobrot/helper_funcs/extract_link_from_message.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K 4 | 5 | import logging 6 | 7 | import aiohttp 8 | from pyrogram.types import MessageEntity 9 | from tobrot import TG_OFFENSIVE_API, LOGGER 10 | 11 | 12 | def extract_url_from_entity(entities: MessageEntity, text: str): 13 | url = None 14 | for entity in entities: 15 | if entity.type == "text_link": 16 | url = entity.url 17 | elif entity.type == "url": 18 | o = entity.offset 19 | l = entity.length 20 | url = text[o : o + l] 21 | return url 22 | 23 | 24 | async def extract_link(message, type_o_request): 25 | custom_file_name = None 26 | url = None 27 | youtube_dl_username = None 28 | youtube_dl_password = None 29 | 30 | if message is None: 31 | url = None 32 | custom_file_name = None 33 | 34 | elif message.text is not None: 35 | if message.text.lower().startswith("magnet:"): 36 | url = message.text.strip() 37 | 38 | elif "|" in message.text: 39 | url_parts = message.text.split("|") 40 | if len(url_parts) == 2: 41 | url = url_parts[0] 42 | custom_file_name = url_parts[1] 43 | elif len(url_parts) == 4: 44 | url = url_parts[0] 45 | custom_file_name = url_parts[1] 46 | youtube_dl_username = url_parts[2] 47 | youtube_dl_password = url_parts[3] 48 | 49 | elif message.entities is not None: 50 | url = extract_url_from_entity(message.entities, message.text) 51 | 52 | else: 53 | url = message.text.strip() 54 | 55 | elif message.document is not None: 56 | if message.document.file_name.lower().endswith(".torrent"): 57 | url = await message.download() 58 | custom_file_name = message.caption 59 | 60 | elif message.caption is not None: 61 | if "|" in message.caption: 62 | url_parts = message.caption.split("|") 63 | if len(url_parts) == 2: 64 | url = url_parts[0] 65 | custom_file_name = url_parts[1] 66 | elif len(url_parts) == 4: 67 | url = url_parts[0] 68 | custom_file_name = url_parts[1] 69 | youtube_dl_username = url_parts[2] 70 | youtube_dl_password = url_parts[3] 71 | 72 | elif message.caption_entities is not None: 73 | url = extract_url_from_entity(message.caption_entities, message.caption) 74 | 75 | else: 76 | url = message.caption.strip() 77 | 78 | elif message.entities is not None: 79 | url = message.text 80 | 81 | # trim blank spaces from the URL 82 | # might have some issues with #45 83 | if url is not None: 84 | url = url.strip() 85 | if custom_file_name is not None: 86 | custom_file_name = custom_file_name.strip() 87 | # https://stackoverflow.com/a/761825/4723940 88 | if youtube_dl_username is not None: 89 | youtube_dl_username = youtube_dl_username.strip() 90 | if youtube_dl_password is not None: 91 | youtube_dl_password = youtube_dl_password.strip() 92 | 93 | # additional conditional check, 94 | # here to FILTER out BAD URLs 95 | LOGGER.info(TG_OFFENSIVE_API) 96 | if TG_OFFENSIVE_API is not None: 97 | try: 98 | async with aiohttp.ClientSession() as session: 99 | api_url = TG_OFFENSIVE_API.format( 100 | i=url, m=custom_file_name, t=type_o_request 101 | ) 102 | LOGGER.info(api_url) 103 | async with session.get(api_url) as resp: 104 | suats = int(resp.status) 105 | err = await resp.text() 106 | if suats != 200: 107 | url = None 108 | custom_file_name = err 109 | except: 110 | # this might occur in case of a BAD API URL, 111 | # who knows? :\ 112 | pass 113 | 114 | return url, custom_file_name, youtube_dl_username, youtube_dl_password 115 | -------------------------------------------------------------------------------- /tobrot/plugins/new_join_fn.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import pyrogram 4 | from tobrot import * 5 | 6 | from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton 7 | 8 | 9 | async def new_join_f(client, message): 10 | chat_type = message.chat.type 11 | if chat_type != "private": 12 | await message.reply_text( 13 | f"""🙋🏻‍♂️ Hello dear!\n\n This Is A Leech Bot .This Chat Is Not Supposed To Use Me\n\nCurrent CHAT ID: {message.chat.id}""", 14 | parse_mode="html", 15 | reply_markup=InlineKeyboardMarkup( 16 | [ 17 | [ 18 | InlineKeyboardButton('Channel', url='https://t.me/MaxxBots') 19 | ] 20 | ] 21 | ) 22 | ) 23 | # leave chat 24 | await client.leave_chat(chat_id=message.chat.id, delete=True) 25 | # delete all other messages, except for AUTH_CHANNEL 26 | await message.delete(revoke=True) 27 | 28 | 29 | async def help_message_f(client, message): 30 | if UPLOAD_AS_DOC: 31 | utxt = "Document" 32 | else: 33 | utxt = "Streamable" 34 | await message.reply_text( 35 | f"""Available Commands 36 | /{RCLONE_COMMAND} : This will change your drive config on fly.(First one will be default) 37 | 38 | /{CLONE_COMMAND_G}: This command is used to clone gdrive files or folder using gclone. 39 | Syntax:- `[ID of the file or folder][one space][name of your folder only(If the id is of file, don't put anything)]` and then reply /gclone to it. 40 | 41 | /{LOG_COMMAND}: This will send you a txt file of the logs. 42 | 43 | /{YTDL_COMMAND}: This command should be used as reply to a supported link 44 | 45 | /{PYTDL_COMMAND}: This command will download videos from youtube playlist link and will upload to telegram. 46 | 47 | /{GYTDL_COMMAND}: This will download and upload to your cloud. 48 | 49 | /{GPYTDL_COMMAND}: This download youtube playlist and upload to your cloud. 50 | 51 | /{LEECH_COMMAND}: 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] 52 | 53 | /{LEECH_ZIP_COMMAND}: 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] 54 | 55 | /{GLEECH_COMMAND}: 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 cloud using rclone. 56 | 57 | /{GLEECH_ZIP_COMMAND} This command will compress the folder/file and will upload to your cloud. 58 | 59 | /{LEECH_UNZIP_COMMAND}: This will unarchive file and upload to telegram. 60 | 61 | /{GLEECH_UNZIP_COMMAND}: This will unarchive file and upload to cloud. 62 | 63 | /{TELEGRAM_LEECH_COMMAND}: This will mirror the telegram files to ur respective cloud . 64 | 65 | /{TELEGRAM_LEECH_UNZIP_COMMAND}: This will unarchive telegram file and upload to cloud. 66 | 67 | /{GET_SIZE_G}: This will give you total size of your destination folder in cloud. 68 | 69 | /{RENEWME_COMMAND}: This will clear the remains of downloads which are not getting deleted after upload of the file or after /cancel command. 70 | 71 | /{CANCEL_COMMAND_G} [GID]: To cancel ur download 72 | 73 | /{RENAME_COMMAND}: To rename the telegram files. 74 | 75 | Only work with direct link and youtube link for nowIt is like u can add custom name as prefix of the original file name. Like if your file name is gk.txt uploaded will be what u add in CUSTOM_FILE_NAME + gk.txt 76 | 77 | Only works with direct link/youtube link.No magnet or torrent. 78 | 79 | And also added custom name like... 80 | 81 | You have to pass link as www.download.me/gk.txt | new.txt 82 | 83 | the file will be uploaded as new.txt. 84 | 85 | /{SAVE_THUMBNAIL}: Reply To A Photo To Save As Custom Thumbnail 86 | 87 | /{CLEAR_THUMBNAIL}: To Clear Saved Custom Thumbnail 88 | 89 | /{TOGGLE_VID}: To Upload Your Files As Streamable 90 | 91 | /{TOGGLE_DOC}: To Upload Your Files As Documents 92 | 93 | **How to Use....?** 94 | __Send any one of the available command, as a reply to a valid link/magnet/torrent. 👊__ 95 | 96 | **Current Custom Upload Mode:** `{utxt}` 97 | 98 | """, 99 | disable_web_page_preview=True, 100 | ) 101 | -------------------------------------------------------------------------------- /app.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Telegram Torrent Leecher", 3 | "description": "A Telegram Torrent (and youtube-dl) Leecher based on Pyrogram. Powered by @MaxxBots", 4 | "logo": "https://telegra.ph/file/101a7d52e02772152c6e3.jpg", 5 | "keywords": [ 6 | "telegram" 7 | ], 8 | "repository": "https://github.com/MaxxRider/Leech-Pro", 9 | "success_url": "https://t.me/MaxxBotChat", 10 | "website": "https://github.com/MaxxRider/Leech-Pro", 11 | "env": { 12 | "ENV": { 13 | "description": "Setting this to ANYTHING will enable webhooks when in env mode", 14 | "value": "ANYTHING" 15 | }, 16 | "APP_ID": { 17 | "description": "Get this value from https://my.telegram.org", 18 | "value": "" 19 | }, 20 | "API_HASH": { 21 | "description": "Get this value from https://my.telegram.org", 22 | "value": "" 23 | }, 24 | "TG_BOT_TOKEN": { 25 | "description": "get this value from @BotFather", 26 | "value": "" 27 | }, 28 | "AUTH_CHANNEL": { 29 | "description": "should be an integer. The BOT API ID of the Telegram Group, where the Leecher should work., Put Group ID", 30 | "value": "" 31 | }, 32 | "OWNER_ID": { 33 | "description": "should be an integer. ID of owner of bot", 34 | "value": "" 35 | }, 36 | "UPLOAD_AS_DOC": { 37 | "description": "True/False. If true all files will be uploaded as documents. Default is False.", 38 | "required": false 39 | }, 40 | "CHUNK_SIZE": { 41 | "description": "should be an integer", 42 | "value": "128", 43 | "required": false 44 | }, 45 | "ARIA_TWO_STARTED_PORT": { 46 | "description": "should be an integer. The port on which aria2c daemon must start, and keep listening.", 47 | "value": "6800", 48 | "required": false 49 | }, 50 | "EDIT_SLEEP_TIME_OUT": { 51 | "description": "should be an integer. Number of seconds to wait before editing a message.", 52 | "value": "15", 53 | "required": false 54 | }, 55 | "MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START": { 56 | "description": "should be an integer. Number of seconds to wait before cancelling a torrent.", 57 | "required": false 58 | }, 59 | "FINISHED_PROGRESS_STR": { 60 | "description": "should be a single character.", 61 | "required": false 62 | }, 63 | "UN_FINISHED_PROGRESS_STR": { 64 | "description": "should be a single character.", 65 | "required": false 66 | }, 67 | "TG_OFFENSIVE_API": { 68 | "description": "should be an URL accepting the FormParams {i}, {m}, and {t}", 69 | "required": false 70 | }, 71 | "LEECH_COMMAND": { 72 | "description": "Enter your custom leech command like /leech@botname and so on. Default is /leech", 73 | "required": false 74 | }, 75 | "SAVE_THUMBNAIL": { 76 | "description": "For custom thumbnail Command. default is /savethumbnail", 77 | "required": false 78 | }, 79 | "CLEAR_THUMBNAIL": { 80 | "description": "For Delete Thumbnail Command. Default is /clearthumbnail", 81 | "required": false 82 | }, 83 | "INDEX_LINK": { 84 | "description": "Enter your index link:", 85 | "required": false 86 | }, 87 | "GLEECH_COMMAND": { 88 | "description": "Enter your custom gleech command like /gleech1@urgroupname and so on. Default is /gleech", 89 | "required": false 90 | }, 91 | "TELEGRAM_LEECH_COMMAND_G": { 92 | "description": "Enter your custom tleech command like /tleech1@urgroupname and so on. Default is /tleech", 93 | "required": false 94 | }, 95 | "YTDL_COMMAND": { 96 | "description": "Enter your custom ytdl command like ytdl1@urgroupname and so on. Default is /ytdl.", 97 | "required": false 98 | }, 99 | "PYTDL_COMMAND_G": { 100 | "description": "Enter your custom pytdl command like pytdl1@urgroupname and so on. Default is /pytdl.", 101 | "required": false 102 | }, 103 | "CANCEL_COMMAND_G": { 104 | "description": "Enter your custom cancel command like cancel@urgroupname and so on. Default is /cancel.", 105 | "required": false 106 | }, 107 | "GET_SIZE_G": { 108 | "description": "Enter your custom getsize command like getsize@urgroupname and so on. Default is /getsize.", 109 | "required": false 110 | }, 111 | "RCLONE_CONFIG": { 112 | "description": "Enter your copied text from rclone config. Compulsory for /gleech as well as /tleech command ", 113 | "required": false 114 | }, 115 | "DESTINATION_FOLDER": { 116 | "description": "Enter your Cloud folder NAME(not ID😅) in which you want to upload/store your files.", 117 | "required": false 118 | }, 119 | "CUSTOM_FILE_NAME": { 120 | "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.", 121 | "required": false 122 | } 123 | }, 124 | "stack": "container" 125 | } 126 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/display_progress.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 | MaxxRider 4 | 5 | import logging 6 | import math 7 | import os 8 | import time 9 | 10 | from pyrogram.errors.exceptions import FloodWait 11 | from tobrot import ( 12 | EDIT_SLEEP_TIME_OUT, 13 | FINISHED_PROGRESS_STR, 14 | UN_FINISHED_PROGRESS_STR, 15 | gDict, 16 | LOGGER, 17 | ) 18 | from pyrogram import Client 19 | 20 | logging.basicConfig( 21 | level=logging.DEBUG, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s" 22 | ) 23 | logger = logging.getLogger(__name__) 24 | 25 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message 26 | 27 | 28 | 29 | class Progress: 30 | def __init__(self, from_user, client, mess: Message): 31 | self._from_user = from_user 32 | self._client = client 33 | self._mess = mess 34 | self._cancelled = False 35 | 36 | @property 37 | def is_cancelled(self): 38 | chat_id = self._mess.chat.id 39 | mes_id = self._mess.message_id 40 | if gDict[chat_id] and mes_id in gDict[chat_id]: 41 | self._cancelled = True 42 | return self._cancelled 43 | 44 | async def progress_for_pyrogram(self, current, total, ud_type, start): 45 | chat_id = self._mess.chat.id 46 | mes_id = self._mess.message_id 47 | from_user = self._from_user 48 | now = time.time() 49 | diff = now - start 50 | reply_markup = InlineKeyboardMarkup( 51 | [ 52 | [ 53 | InlineKeyboardButton( 54 | "Cancel 🚫", 55 | callback_data=( 56 | f"gUPcancel/{chat_id}/{mes_id}/{from_user}" 57 | ).encode("UTF-8"), 58 | ) 59 | ] 60 | ] 61 | ) 62 | if self.is_cancelled: 63 | LOGGER.info("stopping ") 64 | await self._mess.edit( 65 | f"😔 Cancelled/ERROR: `{ud_type}` ({humanbytes(total)})" 66 | ) 67 | await self._client.stop_transmission() 68 | 69 | if round(diff % float(EDIT_SLEEP_TIME_OUT)) == 0 or current == total: 70 | # if round(current / total * 100, 0) % 5 == 0: 71 | percentage = current * 100 / total 72 | speed = current / diff 73 | elapsed_time = round(diff) * 1000 74 | time_to_completion = round((total - current) / speed) * 1000 75 | estimated_total_time = time_to_completion 76 | 77 | elapsed_time = TimeFormatter(milliseconds=elapsed_time) 78 | estimated_total_time = TimeFormatter(milliseconds=estimated_total_time) 79 | 80 | progress = "\n{0}{1} {2}%\n".format( 81 | ''.join([FINISHED_PROGRESS_STR for i in range(math.floor(percentage / 5))]), 82 | ''.join([UN_FINISHED_PROGRESS_STR for i in range(20 - math.floor(percentage / 5))]), 83 | round(percentage, 2)) 84 | #cpu = "{psutil.cpu_percent()}%" 85 | tmp = progress + "\n**• Total 📀:**`〘{1}〙`\n**• Done ✓ :**` 〘{0}〙`\n**• Speed 🚀 :** `〘{2}〙`\n**• ETA ⏳ :**` 〘{3}〙`".format( 86 | humanbytes(current), 87 | humanbytes(total), 88 | humanbytes(speed), 89 | # elapsed_time if elapsed_time != '' else "0 s", 90 | estimated_total_time if estimated_total_time != "" else "0 s", 91 | #tmp += "\n│"+"\n╰── ⌊ @TGFilmZone ⌉" 92 | ) 93 | try: 94 | if not self._mess.photo: 95 | await self._mess.edit_text( 96 | text="{}\n {}".format(ud_type, tmp), reply_markup=reply_markup 97 | ) 98 | else: 99 | await self._mess.edit_caption( 100 | caption="{}\n {}".format(ud_type, tmp) 101 | ) 102 | except FloodWait as fd: 103 | logger.warning(f"{fd}") 104 | time.sleep(fd.x) 105 | except Exception as ou: 106 | logger.info(ou) 107 | 108 | 109 | def humanbytes(size): 110 | # https://stackoverflow.com/a/49361727/4723940 111 | # 2**10 = 1024 112 | if not size: 113 | return "" 114 | power = 2 ** 10 115 | n = 0 116 | Dic_powerN = {0: " ", 1: "Ki", 2: "Mi", 3: "Gi", 4: "Ti"} 117 | while size > power: 118 | size /= power 119 | n += 1 120 | return str(round(size, 2)) + " " + Dic_powerN[n] + "B" 121 | 122 | 123 | def TimeFormatter(milliseconds: int) -> str: 124 | seconds, milliseconds = divmod(int(milliseconds), 1000) 125 | minutes, seconds = divmod(seconds, 60) 126 | hours, minutes = divmod(minutes, 60) 127 | days, hours = divmod(hours, 24) 128 | tmp = ( 129 | ((str(days) + "d, ") if days else "") 130 | + ((str(hours) + "h, ") if hours else "") 131 | + ((str(minutes) + "m, ") if minutes else "") 132 | + ((str(seconds) + "s, ") if seconds else "") 133 | + ((str(milliseconds) + "ms, ") if milliseconds else "") 134 | ) 135 | return tmp[:-2] 136 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/split_large_files.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Akshay C / Shrimadhav U K / YK 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import time 9 | 10 | from hachoir.metadata import extractMetadata 11 | from hachoir.parser import createParser 12 | from tobrot import LOGGER, MAX_TG_SPLIT_FILE_SIZE, SP_LIT_ALGO_RITH_M 13 | 14 | 15 | async def split_large_files(input_file): 16 | working_directory = os.path.dirname(os.path.abspath(input_file)) 17 | new_working_directory = os.path.join(working_directory, str(time.time())) 18 | # create download directory, if not exist 19 | if not os.path.isdir(new_working_directory): 20 | os.makedirs(new_working_directory) 21 | # if input_file.upper().endswith(("MKV", "MP4", "WEBM", "MP3", "M4A", "FLAC", "WAV")): 22 | """The below logic is DERPed, so removing temporarily 23 | """ 24 | if input_file.upper().endswith(("MKV", "MP4", "WEBM", "AVI", "MOV", "OGG", "WMV", "M4V", "TS", "MPG", "MTS", "M2TS", "3GP")): 25 | # handle video / audio files here 26 | metadata = extractMetadata(createParser(input_file)) 27 | total_duration = 0 28 | if metadata.has("duration"): 29 | total_duration = metadata.get("duration").seconds 30 | # proprietary logic to get the seconds to trim (at) 31 | LOGGER.info(total_duration) 32 | total_file_size = os.path.getsize(input_file) 33 | LOGGER.info(total_file_size) 34 | minimum_duration = (total_duration / total_file_size) * (MAX_TG_SPLIT_FILE_SIZE) 35 | # casting to int cuz float Time Stamp can cause errors 36 | minimum_duration = int(minimum_duration) 37 | 38 | LOGGER.info(minimum_duration) 39 | # END: proprietary 40 | start_time = 0 41 | end_time = minimum_duration 42 | base_name = os.path.basename(input_file) 43 | input_extension = base_name.split(".")[-1] 44 | LOGGER.info(input_extension) 45 | 46 | i = 0 47 | flag = False 48 | 49 | while end_time <= total_duration: 50 | LOGGER.info(i) 51 | # file name generate 52 | parted_file_name = "{}_PART_{}.{}".format( 53 | str(base_name), str(i).zfill(5), str(input_extension) 54 | ) 55 | 56 | output_file = os.path.join(new_working_directory, parted_file_name) 57 | LOGGER.info(output_file) 58 | LOGGER.info( 59 | await cult_small_video( 60 | input_file, output_file, str(start_time), str(end_time) 61 | ) 62 | ) 63 | LOGGER.info(f"Start time {start_time}, End time {end_time}, Itr {i}") 64 | 65 | # adding offset of 3 seconds to ensure smooth playback 66 | start_time = end_time - 3 67 | end_time = end_time + minimum_duration 68 | i = i + 1 69 | 70 | if (end_time > total_duration) and not flag: 71 | end_time = total_duration 72 | flag = True 73 | elif flag: 74 | break 75 | 76 | elif SP_LIT_ALGO_RITH_M.lower() == "hjs": 77 | # handle normal files here 78 | o_d_t = os.path.join(new_working_directory, os.path.basename(input_file)) 79 | o_d_t = o_d_t + "." 80 | file_genertor_command = [ 81 | "split", 82 | "--numeric-suffixes=1", 83 | "--suffix-length=5", 84 | f"--bytes={MAX_TG_SPLIT_FILE_SIZE}", 85 | input_file, 86 | o_d_t, 87 | ] 88 | await run_comman_d(file_genertor_command) 89 | 90 | elif SP_LIT_ALGO_RITH_M.lower() == "rar": 91 | o_d_t = os.path.join( 92 | new_working_directory, 93 | os.path.basename(input_file), 94 | ) 95 | LOGGER.info(o_d_t) 96 | file_genertor_command = [ 97 | "rar", 98 | "a", 99 | f"-v{MAX_TG_SPLIT_FILE_SIZE}b", 100 | "-m0", 101 | o_d_t, 102 | input_file, 103 | ] 104 | await run_comman_d(file_genertor_command) 105 | try: 106 | os.remove(input_file) 107 | except Exception as r: 108 | LOGGER.error(r) 109 | return new_working_directory 110 | 111 | 112 | async def cult_small_video(video_file, out_put_file_name, start_time, end_time): 113 | file_genertor_command = [ 114 | "ffmpeg", 115 | "-hide_banner", 116 | "-i", 117 | video_file, 118 | "-ss", 119 | start_time, 120 | "-to", 121 | end_time, 122 | "-async", 123 | "1", 124 | "-strict", 125 | "-2", 126 | "-c", 127 | "copy", 128 | out_put_file_name, 129 | ] 130 | process = await asyncio.create_subprocess_exec( 131 | *file_genertor_command, 132 | # stdout must a pipe to be accessible as process.stdout 133 | stdout=asyncio.subprocess.PIPE, 134 | stderr=asyncio.subprocess.PIPE, 135 | ) 136 | # Wait for the subprocess to finish 137 | stdout, stderr = await process.communicate() 138 | e_response = stderr.decode().strip() 139 | t_response = stdout.decode().strip() 140 | LOGGER.info(t_response) 141 | return out_put_file_name 142 | 143 | 144 | async def run_comman_d(command_list): 145 | process = await asyncio.create_subprocess_exec( 146 | *command_list, 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 | return t_response, e_response 156 | -------------------------------------------------------------------------------- /tobrot/plugins/call_back_button_handler.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 | MaxxRider 4 | 5 | import logging 6 | import os 7 | import shutil 8 | 9 | from pyrogram.types import CallbackQuery 10 | from tobrot import AUTH_CHANNEL, MAX_MESSAGE_LENGTH, LOGGER, gDict 11 | from tobrot.helper_funcs.admin_check import AdminCheck 12 | from tobrot.helper_funcs.download_aria_p_n import aria_start 13 | from tobrot.helper_funcs.youtube_dl_button import youtube_dl_call_back 14 | from tobrot.plugins.choose_rclone_config import rclone_button_callback 15 | from tobrot.plugins.status_message_fn import cancel_message_f 16 | 17 | 18 | async def button(bot, update: CallbackQuery): 19 | cb_data = update.data 20 | try: 21 | g = await AdminCheck(bot, update.message.chat.id, update.from_user.id) 22 | except Exception as ee: 23 | LOGGER.info(ee) 24 | if cb_data.startswith("gUPcancel"): 25 | cmf = cb_data.split("/") 26 | chat_id, mes_id, from_usr = cmf[1], cmf[2], cmf[3] 27 | if (int(update.from_user.id) == int(from_usr)) or g: 28 | await bot.answer_callback_query( 29 | update.id, text="Trying to cancel...", show_alert=False 30 | ) 31 | gDict[int(chat_id)].append(int(mes_id)) 32 | else: 33 | await bot.answer_callback_query( 34 | callback_query_id=update.id, 35 | text="This Is Not Your Leech. So, dont touch on this...😡😡", 36 | show_alert=True, 37 | cache_time=0, 38 | ) 39 | return 40 | if "|" in cb_data: 41 | await bot.answer_callback_query( 42 | update.id, text="trying to download...", show_alert=False 43 | ) 44 | await youtube_dl_call_back(bot, update) 45 | return 46 | if cb_data.startswith("rclone"): 47 | await bot.answer_callback_query( 48 | update.id, text="choose rclone config...", show_alert=False 49 | ) 50 | await rclone_button_callback(bot, update) 51 | return 52 | # todo - remove this code if not needed in future 53 | if cb_data.startswith("cancel"): 54 | if (update.from_user.id == update.message.reply_to_message.from_user.id) or g: 55 | await bot.answer_callback_query( 56 | update.id, text="trying to cancel...", show_alert=False 57 | ) 58 | if len(cb_data) > 1: 59 | i_m_s_e_g = await update.message.reply_to_message.reply_text( 60 | "checking..?", quote=True 61 | ) 62 | aria_i_p = await aria_start() 63 | g_id = cb_data.split()[-1] 64 | LOGGER.info(g_id) 65 | try: 66 | downloads = aria_i_p.get_download(g_id) 67 | file_name = downloads.name 68 | LOGGER.info( 69 | aria_i_p.remove( 70 | downloads=[downloads], force=True, files=True, clean=True 71 | ) 72 | ) 73 | if os.path.exists(file_name): 74 | if os.path.isdir(file_name): 75 | shutil.rmtree(file_name) 76 | else: 77 | os.remove(file_name) 78 | await i_m_s_e_g.edit_text( 79 | f"Leech Cancelled by {update.from_user.first_name}" 80 | ) 81 | except Exception as e: 82 | await i_m_s_e_g.edit_text("FAILED\n\n" + str(e) + "\n#error") 83 | else: 84 | await bot.answer_callback_query( 85 | callback_query_id=update.id, 86 | text="who are you? 🤪🤔🤔🤔", 87 | show_alert=True, 88 | cache_time=0, 89 | ) 90 | elif cb_data == "fuckingdo": 91 | if (update.from_user.id in AUTH_CHANNEL) or g: 92 | await bot.answer_callback_query( 93 | update.id, text="trying to delete...", show_alert=False 94 | ) 95 | g_d_list = [ 96 | "app.json", 97 | "venv", 98 | "rclone.conf", 99 | "rclone_bak.conf", 100 | ".gitignore", 101 | "_config.yml", 102 | "COPYING", 103 | "Dockerfile", 104 | "extract", 105 | "Procfile", 106 | ".heroku", 107 | ".profile.d", 108 | "rclone.jpg", 109 | "README.md", 110 | "requirements.txt", 111 | "runtime.txt", 112 | "start.sh", 113 | "tobrot", 114 | "gautam", 115 | "Torrentleech-Gdrive.txt", 116 | "vendor", 117 | "LeechBot.session", 118 | "LeechBot.session-journal", 119 | "config.env", 120 | "sample_config.env", 121 | ] 122 | g_list = os.listdir() 123 | LOGGER.info(g_list) 124 | g_del_list = list(set(g_list) - set(g_d_list)) 125 | LOGGER.info(g_del_list) 126 | if len(g_del_list) != 0: 127 | for f in g_del_list: 128 | if os.path.isfile(f): 129 | os.remove(f) 130 | else: 131 | shutil.rmtree(f) 132 | await update.message.edit_text(f"Deleted {len(g_del_list)} objects 🚮") 133 | else: 134 | await update.message.edit_text("Nothing to clear 🙄") 135 | else: 136 | await update.message.edit_text("You are not allowed to do that 🤭") 137 | elif cb_data == "fuckoff": 138 | await bot.answer_callback_query( 139 | update.id, text="trying to cancel...", show_alert=False 140 | ) 141 | await update.message.edit_text("Okay! fine 🤬") -------------------------------------------------------------------------------- /tobrot/helper_funcs/create_compressed_archive.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import shutil 9 | import subprocess 10 | 11 | from tobrot import LOGGER 12 | 13 | 14 | async def create_archive(input_directory): 15 | return_name = None 16 | if os.path.exists(input_directory): 17 | base_dir_name = os.path.basename(input_directory) 18 | compressed_file_name = f"{base_dir_name}.tar.gz" 19 | # #BlameTelegram 20 | suffix_extention_length = 1 + 3 + 1 + 2 21 | if len(base_dir_name) > (64 - suffix_extention_length): 22 | compressed_file_name = base_dir_name[0 : (64 - suffix_extention_length)] 23 | compressed_file_name += ".tar.gz" 24 | # fix for https://t.me/c/1434259219/13344 25 | file_genertor_command = [ 26 | "tar", 27 | "-zcvf", 28 | compressed_file_name, 29 | f"{input_directory}", 30 | ] 31 | process = await asyncio.create_subprocess_exec( 32 | *file_genertor_command, 33 | # stdout must a pipe to be accessible as process.stdout 34 | stdout=asyncio.subprocess.PIPE, 35 | stderr=asyncio.subprocess.PIPE, 36 | ) 37 | # Wait for the subprocess to finish 38 | stdout, stderr = await process.communicate() 39 | LOGGER.error(stderr.decode().strip()) 40 | if os.path.exists(compressed_file_name): 41 | try: 42 | shutil.rmtree(input_directory) 43 | except: 44 | pass 45 | return_name = compressed_file_name 46 | return return_name 47 | 48 | 49 | # @gautamajay52 50 | 51 | 52 | async def unzip_me(input_directory): 53 | return_name = None 54 | if os.path.exists(input_directory): 55 | base_dir_name = os.path.basename(input_directory) 56 | # uncompressed_file_name = os.path.splitext(base_dir_name)[0] 57 | uncompressed_file_name = get_base_name(base_dir_name) 58 | LOGGER.info(uncompressed_file_name) 59 | g_cmd = ["./extract", f"{input_directory}"] 60 | ga_utam = await asyncio.create_subprocess_exec( 61 | *g_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 62 | ) 63 | # Wait for the subprocess to finish 64 | gau, tam = await ga_utam.communicate() 65 | LOGGER.info(gau.decode().strip()) 66 | LOGGER.info(tam.decode().strip()) 67 | if os.path.exists(uncompressed_file_name): 68 | try: 69 | os.remove(input_directory) 70 | except: 71 | pass 72 | return_name = uncompressed_file_name 73 | return return_name 74 | 75 | 76 | # 77 | 78 | 79 | async def untar_me(input_directory): 80 | return_name = None 81 | if os.path.exists(input_directory): 82 | print(input_directory) 83 | base_dir_name = os.path.basename(input_directory) 84 | uncompressed_file_name = os.path.splitext(base_dir_name)[0] 85 | m_k_gaut = ["mkdir", f"{uncompressed_file_name}"] 86 | await asyncio.create_subprocess_exec( 87 | *m_k_gaut, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 88 | ) 89 | g_cmd_t = [ 90 | "tar", 91 | "-xvf", 92 | f"/app/{base_dir_name}", 93 | "-C", 94 | f"{uncompressed_file_name}", 95 | ] 96 | bc_kanger = await asyncio.create_subprocess_exec( 97 | *g_cmd_t, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 98 | ) 99 | # Wait for the subprocess to finish 100 | mc, kanger = await bc_kanger.communicate() 101 | LOGGER.info(mc) 102 | LOGGER.info(kanger) 103 | # e_response = stderr.decode().strip() 104 | # t_response = stdout.decode().strip() 105 | if os.path.exists(uncompressed_file_name): 106 | try: 107 | os.remove(input_directory) 108 | except: 109 | pass 110 | return_name = uncompressed_file_name 111 | LOGGER.info(return_name) 112 | return return_name 113 | 114 | 115 | # 116 | 117 | 118 | async def unrar_me(input_directory): 119 | return_name = None 120 | if os.path.exists(input_directory): 121 | base_dir_name = os.path.basename(input_directory) 122 | uncompressed_file_name = os.path.splitext(base_dir_name)[0] 123 | m_k_gau = ["mkdir", f"{uncompressed_file_name}"] 124 | await asyncio.create_subprocess_exec( 125 | *m_k_gau, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 126 | ) 127 | print(base_dir_name) 128 | gau_tam_r = ["unrar", "x", f"{base_dir_name}", f"{uncompressed_file_name}"] 129 | jai_hind = await asyncio.create_subprocess_exec( 130 | *gau_tam_r, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 131 | ) 132 | # Wait for the subprocess to finish 133 | jai, hind = await jai_hind.communicate() 134 | LOGGER.info(jai) 135 | LOGGER.info(hind) 136 | # e_response = stderr.decode().strip() 137 | # t_response = stdout.decode().strip() 138 | if os.path.exists(uncompressed_file_name): 139 | try: 140 | os.remove(input_directory) 141 | except: 142 | pass 143 | return_name = uncompressed_file_name 144 | LOGGER.info(return_name) 145 | return return_name 146 | 147 | 148 | def get_base_name(orig_path: str): 149 | if orig_path.endswith(".tar.bz2"): 150 | return orig_path.replace(".tar.bz2", "") 151 | elif orig_path.endswith(".tar.gz"): 152 | return orig_path.replace(".tar.gz", "") 153 | elif orig_path.endswith(".bz2"): 154 | return orig_path.replace(".bz2", "") 155 | elif orig_path.endswith(".gz"): 156 | return orig_path.replace(".gz", "") 157 | elif orig_path.endswith(".tar"): 158 | return orig_path.replace(".tar", "") 159 | elif orig_path.endswith(".tbz2"): 160 | return orig_path.replace("tbz2", "") 161 | elif orig_path.endswith(".tgz"): 162 | return orig_path.replace(".tgz", "") 163 | elif orig_path.endswith(".zip"): 164 | return orig_path.replace(".zip", "") 165 | elif orig_path.endswith(".7z"): 166 | return orig_path.replace(".7z", "") 167 | elif orig_path.endswith(".Z"): 168 | return orig_path.replace(".Z", "") 169 | elif orig_path.endswith(".rar"): 170 | return orig_path.replace(".rar", "") 171 | else: 172 | raise Exception("File format not supported for extraction") 173 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/direct_link_generator.py: -------------------------------------------------------------------------------- 1 | # Copyright (C) 2019 The Raphielscape Company LLC. 2 | # 3 | # Licensed under the Raphielscape Public License, Version 1.c (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # 6 | """ Helper Module containing various sites direct links generators. This module is copied and modified as per need 7 | from https://github.com/AvinashReddy3108/PaperplaneExtended . I hereby take no credit of the following code other 8 | than the modifications. See https://github.com/AvinashReddy3108/PaperplaneExtended/commits/master/userbot/modules/direct_links.py 9 | for original authorship. """ 10 | 11 | import json 12 | import re 13 | import urllib.parse 14 | from os import popen 15 | from random import choice 16 | from js2py import EvalJs 17 | import requests 18 | from bs4 import BeautifulSoup 19 | 20 | from tobrot.helper_funcs.exceptions import DirectDownloadLinkException 21 | 22 | 23 | def direct_link_generator(text_url: str): 24 | """ direct links generator """ 25 | if not text_url: 26 | raise DirectDownloadLinkException("`No links found!`") 27 | elif 'zippyshare.com' in text_url: 28 | return zippy_share(text_url) 29 | elif 'yadi.sk' in text_url: 30 | return yandex_disk(text_url) 31 | elif 'cloud.mail.ru' in text_url: 32 | return cm_ru(text_url) 33 | elif 'mediafire.com' in text_url: 34 | return mediafire(text_url) 35 | elif 'osdn.net' in text_url: 36 | return osdn(text_url) 37 | elif 'github.com' in text_url: 38 | return github(text_url) 39 | elif 'racaty.net' in text_url: 40 | return racaty(text_url) 41 | else: 42 | raise DirectDownloadLinkException(f'No Direct link function found for {text_url}') 43 | 44 | 45 | def zippy_share(url: str) -> str: 46 | link = re.findall("https:/.(.*?).zippyshare", url)[0] 47 | response_content = (requests.get(url)).content 48 | bs_obj = BeautifulSoup(response_content, "lxml") 49 | 50 | try: 51 | js_script = bs_obj.find("div", {"class": "center",}).find_all( 52 | "script" 53 | )[1] 54 | except: 55 | js_script = bs_obj.find("div", {"class": "right",}).find_all( 56 | "script" 57 | )[0] 58 | 59 | js_content = re.findall(r'\.href.=."/(.*?)";', str(js_script)) 60 | js_content = 'var x = "/' + js_content[0] + '"' 61 | 62 | evaljs = EvalJs() 63 | setattr(evaljs, "x", None) 64 | evaljs.execute(js_content) 65 | js_content = getattr(evaljs, "x") 66 | 67 | return f"https://{link}.zippyshare.com{js_content}" 68 | 69 | 70 | def yandex_disk(url: str) -> str: 71 | """ Yandex.Disk direct links generator 72 | Based on https://github.com/wldhx/yadisk-direct""" 73 | try: 74 | text_url = re.findall(r'\bhttps?://.*yadi\.sk\S+', url)[0] 75 | except IndexError: 76 | reply = "`No Yandex.Disk links found`\n" 77 | return reply 78 | api = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}' 79 | try: 80 | dl_url = requests.get(api.format(text_url)).json()['href'] 81 | return dl_url 82 | except KeyError: 83 | raise DirectDownloadLinkException("`Error: File not found / Download limit reached`\n") 84 | 85 | 86 | def cm_ru(url: str) -> str: 87 | """ cloud.mail.ru direct links generator 88 | Using https://github.com/JrMasterModelBuilder/cmrudl.py""" 89 | reply = '' 90 | try: 91 | text_url = re.findall(r'\bhttps?://.*cloud\.mail\.ru\S+', url)[0] 92 | except IndexError: 93 | raise DirectDownloadLinkException("`No cloud.mail.ru links found`\n") 94 | command = f'vendor/cmrudl.py/cmrudl -s {text_url}' 95 | result = popen(command).read() 96 | result = result.splitlines()[-1] 97 | try: 98 | data = json.loads(result) 99 | except json.decoder.JSONDecodeError: 100 | raise DirectDownloadLinkException("`Error: Can't extract the link`\n") 101 | dl_url = data['download'] 102 | return dl_url 103 | 104 | 105 | def mediafire(url: str) -> str: 106 | """ MediaFire direct links generator """ 107 | try: 108 | text_url = re.findall(r'\bhttps?://.*mediafire\.com\S+', url)[0] 109 | except IndexError: 110 | raise DirectDownloadLinkException("`No MediaFire links found`\n") 111 | page = BeautifulSoup(requests.get(text_url).content, 'lxml') 112 | info = page.find('a', {'aria-label': 'Download file'}) 113 | dl_url = info.get('href') 114 | return dl_url 115 | 116 | 117 | def osdn(url: str) -> str: 118 | """ OSDN direct links generator """ 119 | osdn_link = 'https://osdn.net' 120 | try: 121 | text_url = re.findall(r'\bhttps?://.*osdn\.net\S+', url)[0] 122 | except IndexError: 123 | raise DirectDownloadLinkException("`No OSDN links found`\n") 124 | page = BeautifulSoup( 125 | requests.get(text_url, allow_redirects=True).content, 'lxml') 126 | info = page.find('a', {'class': 'mirror_link'}) 127 | text_url = urllib.parse.unquote(osdn_link + info['href']) 128 | mirrors = page.find('form', {'id': 'mirror-select-form'}).findAll('tr') 129 | urls = [] 130 | for data in mirrors[1:]: 131 | mirror = data.find('input')['value'] 132 | urls.append(re.sub(r'm=(.*)&f', f'm={mirror}&f', text_url)) 133 | return urls[0] 134 | 135 | 136 | def github(url: str) -> str: 137 | """ GitHub direct links generator """ 138 | try: 139 | text_url = re.findall(r'\bhttps?://.*github\.com.*releases\S+', url)[0] 140 | except IndexError: 141 | raise DirectDownloadLinkException("`No GitHub Releases links found`\n") 142 | download = requests.get(text_url, stream=True, allow_redirects=False) 143 | try: 144 | dl_url = download.headers["location"] 145 | return dl_url 146 | except KeyError: 147 | raise DirectDownloadLinkException("`Error: Can't extract the link`\n") 148 | 149 | 150 | def useragent(): 151 | """ 152 | useragent random setter 153 | """ 154 | useragents = BeautifulSoup( 155 | requests.get( 156 | 'https://developers.whatismybrowser.com/' 157 | 'useragents/explore/operating_system_name/android/').content, 158 | 'lxml').findAll('td', {'class': 'useragent'}) 159 | user_agent = choice(useragents) 160 | return user_agent.text 161 | 162 | def racaty(url: str) -> str: 163 | dl_url = '' 164 | try: 165 | text_url = re.findall(r'\bhttps?://.*racaty\.net\S+', url)[0] 166 | except IndexError: 167 | raise DirectDownloadLinkException("`No Racaty links found`\n") 168 | reqs=requests.get(text_url) 169 | bss=BeautifulSoup(reqs.text,'html.parser') 170 | op=bss.find('input',{'name':'op'})['value'] 171 | id=bss.find('input',{'name':'id'})['value'] 172 | rep=requests.post(text_url,data={'op':op,'id':id}) 173 | bss2=BeautifulSoup(rep.text,'html.parser') 174 | dl_url=bss2.find('a',{'id':'uniqueExpirylink'})['href'] 175 | return dl_url -------------------------------------------------------------------------------- /tobrot/helper_funcs/cloneHelper.py: -------------------------------------------------------------------------------- 1 | # This is code to clone the gdrive link using the gclone, all credit goes to the developer who has developed the rclone/glclone 2 | #!/usr/bin/env python3 3 | # -*- coding: utf-8 -*- 4 | # (c) gautamajay52 5 | # (c) MaxxRider 6 | 7 | import asyncio 8 | import logging 9 | import os 10 | import re 11 | import subprocess 12 | 13 | import pyrogram.types as pyrogram 14 | import requests 15 | from tobrot import ( 16 | DESTINATION_FOLDER, 17 | DOWNLOAD_LOCATION, 18 | EDIT_SLEEP_TIME_OUT, 19 | INDEX_LINK, 20 | LOGGER, 21 | RCLONE_CONFIG, 22 | TG_MAX_FILE_SIZE, 23 | UPLOAD_AS_DOC, 24 | ) 25 | 26 | 27 | class CloneHelper: 28 | def __init__(self, mess): 29 | self.g_id = "" 30 | self.mess = mess 31 | self.name = "" 32 | self.out = b"" 33 | self.err = b"" 34 | self.lsg = "" 35 | self.filee = "" 36 | self.u_id = self.mess.from_user.id 37 | self.dname = "" 38 | 39 | def config(self): 40 | if not os.path.exists("rclone.conf"): 41 | with open("rclone.conf", "w+", newline="\n", encoding="utf-8") as fole: 42 | fole.write(f"{RCLONE_CONFIG}") 43 | if os.path.exists("rclone.conf"): 44 | with open("rclone.conf", "r+") as file: 45 | con = file.read() 46 | self.dname = re.findall("\[(.*)\]", con)[0] 47 | 48 | def get_id(self): 49 | mes = self.mess 50 | txt = mes.reply_to_message.text 51 | LOGGER.info(txt) 52 | mess = txt.split(" ", maxsplit=1) 53 | if len(mess) == 2: 54 | self.g_id = mess[0] 55 | LOGGER.info(self.g_id) 56 | self.name = mess[1] 57 | LOGGER.info(self.name) 58 | else: 59 | self.g_id = mess[0] 60 | LOGGER.info(self.g_id) 61 | self.name = "" 62 | return self.g_id, self.name 63 | 64 | async def link_gen_size(self): 65 | if self.name is not None: 66 | _drive = "" 67 | if self.name == self.filee: 68 | _flag = "--files-only" 69 | _up = "File" 70 | _ui = "" 71 | else: 72 | _flag = "--dirs-only" 73 | _up = "Folder" 74 | _drive = "folderba" 75 | _ui = "/" 76 | g_name = re.escape(self.name) 77 | LOGGER.info(g_name) 78 | destination = f"{DESTINATION_FOLDER}" 79 | 80 | with open("filter1.txt", "w+", encoding="utf-8") as filter1: 81 | print(f"+ {g_name}{_ui}\n- *", file=filter1) 82 | 83 | g_a_u = [ 84 | "rclone", 85 | "lsf", 86 | "--config=./rclone.conf", 87 | "-F", 88 | "i", 89 | "--filter-from=./filter1.txt", 90 | f"{_flag}", 91 | f"{self.dname}:{destination}", 92 | ] 93 | LOGGER.info(g_a_u) 94 | gau_tam = await asyncio.create_subprocess_exec( 95 | *g_a_u, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 96 | ) 97 | gau, tam = await gau_tam.communicate() 98 | LOGGER.info(gau) 99 | gautam = gau.decode("utf-8") 100 | LOGGER.info(gautam) 101 | LOGGER.info(tam.decode("utf-8")) 102 | 103 | if _drive == "folderba": 104 | gautii = f"https://drive.google.com/folderview?id={gautam}" 105 | else: 106 | gautii = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk" 107 | 108 | LOGGER.info(gautii) 109 | gau_link = re.search("(?Phttps?://[^\s]+)", gautii).group("url") 110 | LOGGER.info(gau_link) 111 | button = [] 112 | button.append( 113 | [ 114 | pyrogram.InlineKeyboardButton( 115 | text="🔮 CLOUD LINK", url=f"{gau_link}" 116 | ) 117 | ] 118 | ) 119 | if INDEX_LINK: 120 | if _flag == "--files-only": 121 | indexurl = f"{INDEX_LINK}/{self.name}" 122 | else: 123 | indexurl = f"{INDEX_LINK}/{self.name}/" 124 | tam_link = requests.utils.requote_uri(indexurl) 125 | LOGGER.info(tam_link) 126 | button.append( 127 | [ 128 | pyrogram.InlineKeyboardButton( 129 | text="💡 𝐈𝐧𝐝𝐞𝐱 𝐋𝐢𝐧𝐤", url=f"{tam_link}" 130 | ) 131 | ] 132 | ) 133 | button_markup = pyrogram.InlineKeyboardMarkup(button) 134 | msg = await self.lsg.edit_text( 135 | f"🐈: {_up} Cloned successfully in your Cloud 😊\ 136 | \n📀 Info: Calculating...", 137 | reply_markup=button_markup, 138 | parse_mode="html", 139 | ) 140 | g_cmd = [ 141 | "rclone", 142 | "size", 143 | "--config=rclone.conf", 144 | f"{self.dname}:{destination}/{self.name}", 145 | ] 146 | LOGGER.info(g_cmd) 147 | gaut_am = await asyncio.create_subprocess_exec( 148 | *g_cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 149 | ) 150 | gaut, am = await gaut_am.communicate() 151 | g_autam = gaut.decode("utf-8") 152 | LOGGER.info(g_autam) 153 | LOGGER.info(am.decode("utf-8")) 154 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 155 | await msg.edit_text( 156 | f"🐈: {_up} Cloned successfully in your Cloud 😊\ 157 | \n📀 Info:\n{g_autam}", 158 | reply_markup=button_markup, 159 | parse_mode="html", 160 | ) 161 | 162 | async def gcl(self): 163 | self.lsg = await self.mess.reply_text(f"Cloning...you should wait 🤒") 164 | destination = f"{DESTINATION_FOLDER}" 165 | idd = "{" f"{self.g_id}" "}" 166 | cmd = [ 167 | "/app/gautam/gclone", 168 | "copy", 169 | "--config=rclone.conf", 170 | f"{self.dname}:{idd}", 171 | f"{self.dname}:{destination}/{self.name}", 172 | "-v", 173 | "--drive-server-side-across-configs", 174 | "--transfers=16", 175 | "--checkers=20", 176 | ] 177 | LOGGER.info(cmd) 178 | pro = await asyncio.create_subprocess_exec( 179 | *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 180 | ) 181 | p, e = await pro.communicate() 182 | self.out = p 183 | LOGGER.info(self.out) 184 | err = e.decode() 185 | LOGGER.info(err) 186 | LOGGER.info(self.out.decode()) 187 | 188 | if self.name == "": 189 | reg_f = "INFO(.*)(:)(.*)(:) (Copied)" 190 | file_n = re.findall(reg_f, err) 191 | LOGGER.info(file_n[0][2].strip()) 192 | self.name = file_n[0][2].strip() 193 | self.filee = self.name 194 | -------------------------------------------------------------------------------- /tobrot/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 | MaxxRider 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import time 9 | from collections import defaultdict 10 | from logging.handlers import RotatingFileHandler 11 | from sys import exit 12 | import urllib.request 13 | import dotenv 14 | 15 | from pyrogram import Client 16 | 17 | if os.path.exists("TorrentLeech-Gdrive.txt"): 18 | with open("Torrentleech-Gdrive.txt", "r+") as f_d: 19 | f_d.truncate(0) 20 | 21 | # the logging things 22 | logging.basicConfig( 23 | level=logging.DEBUG, 24 | format="%(asctime)s - %(levelname)s - %(message)s [%(filename)s:%(lineno)d]", 25 | datefmt="%d-%b-%y %H:%M:%S", 26 | handlers=[ 27 | RotatingFileHandler( 28 | "Torrentleech-Gdrive.txt", maxBytes=50000000, backupCount=10 29 | ), 30 | logging.StreamHandler(), 31 | ], 32 | ) 33 | logging.getLogger("pyrogram").setLevel(logging.ERROR) 34 | logging.getLogger("urllib3").setLevel(logging.WARNING) 35 | logging.getLogger("PIL").setLevel(logging.WARNING) 36 | 37 | LOGGER = logging.getLogger(__name__) 38 | 39 | user_specific_config=dict() 40 | 41 | dotenv.load_dotenv("config.env") 42 | 43 | # checking compulsory variable 44 | for imp in ["TG_BOT_TOKEN", "APP_ID", "API_HASH", "OWNER_ID", "AUTH_CHANNEL"]: 45 | try: 46 | value = os.environ[imp] 47 | if not value: 48 | raise KeyError 49 | except KeyError: 50 | LOGGER.critical(f"Oh...{imp} is missing from config.env ... fill that") 51 | exit() 52 | 53 | # The Telegram API things 54 | TG_BOT_TOKEN = os.environ.get("TG_BOT_TOKEN", "") 55 | APP_ID = int(os.environ.get("APP_ID", "12345")) 56 | API_HASH = os.environ.get("API_HASH") 57 | OWNER_ID = int(os.environ.get("OWNER_ID", "539295917")) 58 | 59 | # Get these values from my.telegram.org 60 | # to store the channel ID who are authorized to use the bot 61 | AUTH_CHANNEL = [int(x) for x in os.environ.get("AUTH_CHANNEL", "539295917").split()] 62 | 63 | # the download location, where the HTTP Server runs 64 | DOWNLOAD_LOCATION = "./DOWNLOADS" 65 | # Telegram maximum file upload size 66 | MAX_FILE_SIZE = 50000000 67 | TG_MAX_FILE_SIZE = 2097152000 68 | FREE_USER_MAX_FILE_SIZE = 50000000 69 | AUTH_CHANNEL.append(539295917) 70 | AUTH_CHANNEL.append(OWNER_ID) 71 | # chunk size that should be used with requests 72 | CHUNK_SIZE = int(os.environ.get("CHUNK_SIZE", "128")) 73 | # default thumbnail to be used in the videos 74 | DEF_THUMB_NAIL_VID_S = os.environ.get("DEF_THUMB_NAIL_VID_S", "https://telegra.ph/file/3a7f09b89943b51cdba38.jpg") 75 | # maximum message length in Telegram 76 | MAX_MESSAGE_LENGTH = 4096 77 | # set timeout for subprocess 78 | PROCESS_MAX_TIMEOUT = 3600 79 | # 80 | SP_LIT_ALGO_RITH_M = os.environ.get("SP_LIT_ALGO_RITH_M", "hjs") 81 | ARIA_TWO_STARTED_PORT = int(os.environ.get("ARIA_TWO_STARTED_PORT", "6800")) 82 | EDIT_SLEEP_TIME_OUT = int(os.environ.get("EDIT_SLEEP_TIME_OUT", "15")) 83 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START = int(os.environ.get("MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START", 600)) 84 | MAX_TG_SPLIT_FILE_SIZE = int(os.environ.get("MAX_TG_SPLIT_FILE_SIZE", "1072864000")) 85 | # add config vars for the display progress 86 | FINISHED_PROGRESS_STR = os.environ.get("FINISHED_PROGRESS_STR", "█") 87 | UN_FINISHED_PROGRESS_STR = os.environ.get("UN_FINISHED_PROGRESS_STR", "░") 88 | # add offensive API 89 | TG_OFFENSIVE_API = os.environ.get("TG_OFFENSIVE_API", None) 90 | CUSTOM_FILE_NAME = os.environ.get("CUSTOM_FILE_NAME", "") 91 | LEECH_COMMAND = os.environ.get("LEECH_COMMAND", "leech") 92 | LEECH_UNZIP_COMMAND = os.environ.get("LEECH_UNZIP_COMMAND", "extract") 93 | LEECH_ZIP_COMMAND = os.environ.get("LEECH_ZIP_COMMAND", "archive") 94 | GLEECH_COMMAND = os.environ.get("GLEECH_COMMAND", "gleech") 95 | GLEECH_UNZIP_COMMAND = os.environ.get("GLEECH_UNZIP_COMMAND", "gleeche_extract") 96 | GLEECH_ZIP_COMMAND = os.environ.get("GLEECH_ZIP_COMMAND", "gleech_archive") 97 | YTDL_COMMAND = os.environ.get("YTDL_COMMAND", "ytdl") 98 | GYTDL_COMMAND = os.environ.get("GYTDL_COMMAND", "gytdl") 99 | RCLONE_CONFIG = os.environ.get("RCLONE_CONFIG", "") 100 | DESTINATION_FOLDER = os.environ.get("DESTINATION_FOLDER", "Maxx-TD") 101 | INDEX_LINK = os.environ.get("INDEX_LINK", "") 102 | TELEGRAM_LEECH_COMMAND = os.environ.get("TELEGRAM_LEECH_COMMAND", "tleech") 103 | TELEGRAM_LEECH_UNZIP_COMMAND = os.environ.get("TELEGRAM_LEECH_UNZIP_COMMAND", "tleechunzip") 104 | CANCEL_COMMAND_G = os.environ.get("CANCEL_COMMAND_G", "cancel") 105 | GET_SIZE_G = os.environ.get("GET_SIZE_G", "getsize") 106 | STATUS_COMMAND = os.environ.get("STATUS_COMMAND", "status") 107 | SAVE_THUMBNAIL = os.environ.get("SAVE_THUMBNAIL", "savethumbnail") 108 | CLEAR_THUMBNAIL = os.environ.get("CLEAR_THUMBNAIL", "clearthumbnail") 109 | UPLOAD_AS_DOC = os.environ.get("UPLOAD_AS_DOC", "False") 110 | PYTDL_COMMAND = os.environ.get("PYTDL_COMMAND", "playlist") 111 | GPYTDL_COMMAND = os.environ.get("GPYTDL_COMMAND", "gpytdl") 112 | LOG_COMMAND = os.environ.get("LOG_COMMAND", "log") 113 | CLONE_COMMAND_G = os.environ.get("CLONE_COMMAND_G", "gclone") 114 | UPLOAD_COMMAND = os.environ.get("UPLOAD_COMMAND", "upload") 115 | RENEWME_COMMAND = os.environ.get("RENEWME_COMMAND", "renewme") 116 | RENAME_COMMAND = os.environ.get("RENAME_COMMAND", "rename") 117 | TOGGLE_VID = os.environ.get("TOGGLE_VID", "togglevideo") 118 | TOGGLE_DOC = os.environ.get("TOGGLE_DOC", "togglefile") 119 | RCLONE_COMMAND = os.environ.get("RCLONE_COMMAND", "rclone") 120 | HELP_COMMAND = os.environ.get("HELP_COMMAND", "help") 121 | BOT_START_TIME = time.time() 122 | # dict to control uploading and downloading 123 | gDict = defaultdict(lambda: []) 124 | # user settings dict #ToDo 125 | user_settings = defaultdict(lambda: {}) 126 | gid_dict = defaultdict(lambda: []) 127 | _lock = asyncio.Lock() 128 | 129 | # Rclone Config Via any raw url 130 | ########################################################################### 131 | try: # 132 | RCLONE_CONF_URL = os.environ.get('RCLONE_CONF_URL', "") # 133 | if len(RCLONE_CONF_URL) == 0: # 134 | RCLONE_CONF_URL = None # 135 | else: # 136 | urllib.request.urlretrieve(RCLONE_CONF_URL, '/app/rclone.conf') # 137 | except KeyError: # 138 | RCLONE_CONF_URL = None # 139 | ########################################################################### 140 | 141 | def multi_rclone_init(): 142 | if RCLONE_CONFIG: 143 | LOGGER.warning("Don't use this var now, put your rclone.conf in root directory") 144 | if not os.path.exists("rclone.conf"): 145 | LOGGER.warning("Sed, No rclone.conf found in root directory") 146 | return 147 | if not os.path.exists("rclone_bak.conf"): # backup rclone.conf file 148 | with open("rclone_bak.conf", "w+", newline="\n", encoding="utf-8") as fole: 149 | with open("rclone.conf", "r") as f: 150 | fole.write(f.read()) 151 | LOGGER.info("rclone.conf backuped to rclone_bak.conf!") 152 | 153 | 154 | multi_rclone_init() 155 | 156 | app = Client("LeechBot", bot_token=TG_BOT_TOKEN, api_id=APP_ID, api_hash=API_HASH, workers=343) 157 | 158 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![MAXX LEECH V2](https://telegra.ph/file/af8f0596124714a17e4e2.png) 2 | 3 | # 🧲 MAXX LEECH PRO 4 | 5 | ## 👉 **Original Repository** 6 | https://github.com/gautamajay52/TorrentLeech-Gdrive 7 | 8 | ![Maxx](https://telegra.ph/file/d18fa7fa33f26f733adb9.png) 9 | 10 | --- 11 | 12 | ## ⚠️ **Please Don't Kill Heroku ☹️** 13 | [![MAXX LEECH](https://telegra.ph/file/29d788a656dd517eafd0a.png)](https://telegram.dog/MaxxBots) 14 | 15 | --- 16 | 17 | # ✨ **Features & Benefits** :- 18 | 19 | ✓ Google Drive link cloning using gclone.(wip) 20 | ✓ Telegram File mirrorring to cloud along with its unzipping, unrar and untar 21 | ✓ Drive/Teamdrive support/All other cloud services rclone.org supports 22 | ✓ Unzip 23 | ✓ Unrar 24 | ✓ Untar 25 | ✓ Custom file name 26 | ✓ Custom commands 27 | ✓ Get total size of your working cloud directory 28 | ✓ You can also upload files downloaded from /ytdl command to gdrive using `/ytdl gdrive` command. 29 | ✓ You can also deploy this on your VPS 30 | ✓ Option to select either video will be uploaded as document or streamable 31 | ✓ Added /renewme command to clear the downloads which are not deleted automatically. 32 | ✓ Added support for youtube playlist 😐 33 | ✓ Renaming of Telegram files support added. 😐 34 | ✓ Changing rclone destination config on fly (By using `/rlcone` in private mode) 35 | ✓ 36 | 37 | --- 38 | 39 | [![Maxx](https://telegra.ph/file/f3f3b950c2904756bb201.png)](https://t.me/MaxxRiderz) 40 | 41 | --- 42 | 43 | # 🔑 **Mandatory Variables** 44 | 45 | ### `TG_BOT_TOKEN` 46 | Get via **@BotFather**. 47 | 48 | ### `APP_ID` & `API_HASH` 49 | https://my.telegram.org/apps 50 | > If Telegram blocked → https://telegram.dog/UseTGXBot 51 | 52 | ### `AUTH_CHANNEL` 53 | Create Supergroup → Add **@GoogleIMGBot** → Send `/id`. 54 | 55 | ### `OWNER_ID` 56 | Bot owner's Telegram ID. 57 | 58 | --- 59 | 60 | [![Maxx](https://telegra.ph/file/7e3a50f29f871defe0bcb.png)](https://t.me/MaxxBots) 61 | 62 | --- 63 | 64 | # 🛠️ **Optional Configuration Variables** 65 | ### *(Tap to Expand * 66 | 67 |
68 | 🔘 CLICK HERE TO VIEW OPTIONAL VARIABLES 69 | 70 |
71 | 72 | * `DOWNLOAD_LOCATION` 73 | 74 | * `MAX_FILE_SIZE` 75 | 76 | * `TG_MAX_FILE_SIZE` 77 | 78 | * `FREE_USER_MAX_FILE_SIZE` 79 | 80 | * `MAX_TG_SPLIT_FILE_SIZE` 81 | 82 | * `CHUNK_SIZE` 83 | 84 | * `MAX_MESSAGE_LENGTH` 85 | 86 | * `PROCESS_MAX_TIMEOUT` 87 | 88 | * `ARIA_TWO_STARTED_PORT` 89 | 90 | * `EDIT_SLEEP_TIME_OUT` 91 | 92 | * `MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START` 93 | 94 | * `FINISHED_PROGRESS_STR` 95 | 96 | * `UN_FINISHED_PROGRESS_STR` 97 | 98 | * `TG_OFFENSIVE_API` 99 | 100 | * `CUSTOM_FILE_NAME` 101 | 102 | * `LEECH_COMMAND` 103 | 104 | * `YTDL_COMMAND` 105 | 106 | * `GYTDL_COMMAND` 107 | 108 | * `GLEECH_COMMAND` 109 | 110 | * `TELEGRAM_LEECH_COMMAND` 111 | 112 | * `TELEGRAM_LEECH_UNZIP_COMMAND` 113 | 114 | * `PYTDL_COMMAND` 115 | 116 | * `CLONE_COMMAND_G` 117 | 118 | * `UPLOAD_COMMAND` 119 | 120 | * `RENEWME_COMMAND` 121 | 122 | * `SAVE_THUMBNAIL` 123 | 124 | * `CLEAR_THUMBNAIL` 125 | 126 | * `GET_SIZE_G` 127 | 128 | * `UPLOAD_AS_DOC`: Takes two option True or False. If True file will be uploaded as document. This is for people who wants video files as document instead of streamable. 129 | 130 | * `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. 131 | 132 | * `DESTINATION_FOLDER`: Name of your folder in ur respective drive where you want to upload the files using the bot. 133 | 134 |
135 | 136 | --- 137 | 138 | # 📌 **Default Commands (when optional vars not set)** 139 | ### *(Tap to Expand)* 140 | 141 |
142 | 🔘 CLICK HERE TO VIEW DEFAULT COMMANDS 143 | 144 |
145 | 146 | 147 | ➢ `/leech` 148 | 149 | ➢ `/ytdl` 150 | 151 | ➢ `/extract` 152 | 153 | ➢ `/savethumbnail` 154 | 155 | ➢ `/deletethumbnail` 156 | 157 | ➢ `/playlist` 158 | 159 | ➢ `/archive` 160 | 161 | ➢ `/togglefile` 162 | 163 | ➢ `/togglevideo` 164 | 165 | ➢ `/rename` 166 | 167 | ➢ `/renewme` 168 | 169 | ➢ `/gleech` 170 | 171 | ➢ `/gpytdl` 172 | 173 | ➢ `/gleech_archive` 174 | 175 | ➢ `/gleech_extract` 176 | 177 | ➢ `/gclone` 178 | 179 | ➢ `/cancel` 180 | 181 | ➢ `/status` 182 | 183 | 184 |
185 | 186 | --- 187 | 188 | [![Maxx](https://telegra.ph/file/3066ec5102c94b8135e09.png)](https://t.me/MaxxBotChat) 189 | 190 | --- 191 | 192 | # 🔴 **Heroku Support Notice** 193 | Heroku works **for now**, but not guaranteed forever because 194 | **torrent workloads violate Heroku policies**. 195 | 196 | --- 197 | 198 | # 📘 **New User? Read Full Guide** 199 | 👉 https://GitHub.com/MaxxRider/About-Leech 200 | 201 | --- 202 | 203 | # ⭐ **Support the Project** 204 | **Please give a ★ on GitHub — it motivates the developer! 😄** 205 | 206 | --- 207 | 208 |

209 | 210 | 211 | 212 |

213 | 214 | --- 215 | 216 | # 🛰️ **DIGITAL REPOSITORY DASHBOARD** 217 | ### *Auto-updating futuristic analytics panel* 218 | 219 |

220 | 221 | 222 | 223 | 224 |
225 | 226 | 227 | 228 | 229 |
230 | 231 | 232 | 233 | 234 | 235 |
236 | 237 | 238 | 239 | 240 | 241 |

242 | 243 | --- 244 | 245 | # 👑 **Credits** 246 | - [GautamKumar](https://github.com/gautamajay52/TorrentLeech-Gdrive) 247 | - [SpEcHiDe](https://github.com/SpEcHiDe/PublicLeech) 248 | - [Rclone Team](https://rclone.org) 249 | - [Dan Tès](https://telegram.dog/haskell) — Creator of Pyrogram 250 | - [Robots](https://telegram.dog/Robots) — Creator of @UploadBot 251 | - [@AjeeshNair](https://telegram.dog/AjeeshNait) — https://torrent.ajee.sh 252 | - @gotstc, @aryanvikash, [@HasibulKabir](https://telegram.dog/HasibulKabir) 253 | 254 | 255 | 256 | ## 🔗 Connect With Me 257 | 258 |

259 | 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | 271 | 272 | 273 | 274 | 275 | 276 |

277 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/youtube_dl_button.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamjay52 | MaxxRider 4 | 5 | import asyncio 6 | import json 7 | import logging 8 | import math 9 | import os 10 | import shutil 11 | import subprocess 12 | import time 13 | from datetime import datetime 14 | 15 | import pyrogram 16 | from tobrot import AUTH_CHANNEL, DOWNLOAD_LOCATION, LOGGER, GYTDL_COMMAND 17 | from tobrot.helper_funcs.upload_to_tg import upload_to_gdrive, upload_to_tg 18 | 19 | 20 | async def youtube_dl_call_back(bot, update): 21 | # LOGGER.info(update) 22 | cb_data = update.data 23 | get_cf_name = update.message.caption 24 | # LOGGER.info(get_cf_name) 25 | cf_name = "" 26 | if "|" in get_cf_name: 27 | cf_name = get_cf_name.split("|", maxsplit=1)[1] 28 | cf_name = cf_name.strip() 29 | # youtube_dl extractors 30 | tg_send_type, youtube_dl_format, youtube_dl_ext = cb_data.split("|") 31 | # 32 | current_user_id = update.message.reply_to_message.from_user.id 33 | current_touched_user_id = update.from_user.id 34 | if current_user_id != current_touched_user_id: 35 | await bot.answer_callback_query( 36 | callback_query_id=update.id, 37 | text="Dont Touch On This. This Leech isnt started by you..😡😡😡", 38 | show_alert=True, 39 | cache_time=0, 40 | ) 41 | return False, None 42 | 43 | user_working_dir = os.path.join(DOWNLOAD_LOCATION, str(current_user_id)) 44 | # create download directory, if not exist 45 | if not os.path.isdir(user_working_dir): 46 | await bot.delete_messages( 47 | chat_id=update.message.chat.id, 48 | message_ids=[ 49 | update.message.message_id, 50 | update.message.reply_to_message.message_id, 51 | ], 52 | revoke=True, 53 | ) 54 | return 55 | save_ytdl_json_path = user_working_dir + "/" + str("ytdleech") + ".json" 56 | try: 57 | with open(save_ytdl_json_path, "r", encoding="utf8") as f: 58 | response_json = json.load(f) 59 | os.remove(save_ytdl_json_path) 60 | except (FileNotFoundError) as e: 61 | await bot.delete_messages( 62 | chat_id=update.message.chat.id, 63 | message_ids=[ 64 | update.message.message_id, 65 | update.message.reply_to_message.message_id, 66 | ], 67 | revoke=True, 68 | ) 69 | return False 70 | # 71 | response_json = response_json[0] 72 | # TODO: temporary limitations 73 | # LOGGER.info(response_json) 74 | # 75 | youtube_dl_url = response_json.get("webpage_url") 76 | LOGGER.info(youtube_dl_url) 77 | # 78 | custom_file_name = "%(title)s.%(ext)s" 79 | # https://superuser.com/a/994060 80 | LOGGER.info(custom_file_name) 81 | # 82 | await update.message.edit_caption(caption="**Trying To Download.... Please wait..**") 83 | 84 | tmp_directory_for_each_user = os.path.join( 85 | DOWNLOAD_LOCATION, str(update.message.message_id) 86 | ) 87 | if not os.path.isdir(tmp_directory_for_each_user): 88 | os.makedirs(tmp_directory_for_each_user) 89 | download_directory = tmp_directory_for_each_user 90 | LOGGER.info(download_directory) 91 | download_directory = os.path.join(tmp_directory_for_each_user, custom_file_name) 92 | LOGGER.info(download_directory) 93 | command_to_exec = [] 94 | # to keep default thumbnail of video which has its thumbnail 95 | thumb_image = None 96 | thumb_image = response_json.get("thumbnail", thumb_image) 97 | if tg_send_type == "audio": 98 | command_to_exec = [ 99 | "yt-dlp", 100 | "-c", 101 | "--prefer-ffmpeg", 102 | "--extract-audio", 103 | "--audio-format", 104 | youtube_dl_ext, 105 | "--audio-quality", 106 | youtube_dl_format, 107 | youtube_dl_url, 108 | "-o", 109 | download_directory, 110 | ] 111 | else: 112 | for for_mat in response_json["formats"]: 113 | format_id = for_mat.get("format_id") 114 | if format_id == youtube_dl_format: 115 | acodec = for_mat.get("acodec") 116 | if acodec == "none": 117 | youtube_dl_format += "+bestaudio" 118 | break 119 | 120 | command_to_exec = [ 121 | "yt-dlp", 122 | "-c", 123 | "--embed-subs", 124 | "-f", 125 | youtube_dl_format, 126 | "--hls-prefer-ffmpeg", 127 | youtube_dl_url, 128 | "-o", 129 | download_directory, 130 | ] 131 | # 132 | command_to_exec.append("--no-warnings") 133 | # command_to_exec.append("--quiet") 134 | command_to_exec.append("--restrict-filenames") 135 | # 136 | if "hotstar" in youtube_dl_url: 137 | command_to_exec.append("--geo-bypass-country") 138 | command_to_exec.append("IN") 139 | LOGGER.info(command_to_exec) 140 | process = await asyncio.create_subprocess_exec( 141 | *command_to_exec, 142 | # stdout must a pipe to be accessible as process.stdout 143 | stdout=asyncio.subprocess.PIPE, 144 | stderr=asyncio.subprocess.PIPE, 145 | ) 146 | # Wait for the subprocess to finish 147 | stdout, stderr = await process.communicate() 148 | e_response = stderr.decode().strip() 149 | t_response = stdout.decode().strip() 150 | # LOGGER.info(e_response) 151 | # LOGGER.info(t_response) 152 | 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." 153 | if e_response and ad_string_to_replace in e_response: 154 | error_message = e_response.replace(ad_string_to_replace, "") 155 | await update.message.edit_caption(caption=error_message) 156 | return False, None 157 | if t_response: 158 | dir_contents = len(os.listdir(tmp_directory_for_each_user)) 159 | await update.message.edit_caption(caption=f"found {dir_contents} files") 160 | user_id = update.from_user.id 161 | # 162 | LOGGER.info(tmp_directory_for_each_user) 163 | for a, _, c in os.walk(tmp_directory_for_each_user): 164 | for d in c: 165 | e = os.path.join(a, d) 166 | gaut_am = os.path.basename(e) 167 | fi_le = e 168 | if cf_name: 169 | fi_le = os.path.join(a, cf_name) 170 | os.rename(e, fi_le) 171 | gaut_am = os.path.basename(fi_le) 172 | 173 | is_cloud = False 174 | comd = update.message.reply_to_message.text 175 | LOGGER.info(comd) 176 | user_command = comd.split()[0] 177 | if user_command == "/" + GYTDL_COMMAND: 178 | is_cloud = True 179 | if is_cloud: 180 | shutil.move(fi_le, "./") 181 | final_response = await upload_to_gdrive( 182 | gaut_am, update.message, update.message.reply_to_message, user_id 183 | ) 184 | else: 185 | final_response = await upload_to_tg( 186 | update.message, 187 | tmp_directory_for_each_user, 188 | user_id, 189 | {}, 190 | bot, 191 | True, 192 | yt_thumb=thumb_image, 193 | ) 194 | LOGGER.info(final_response) 195 | # 196 | try: 197 | shutil.rmtree(tmp_directory_for_each_user) 198 | except: 199 | pass 200 | # 201 | 202 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/youtube_dl_extractor.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | MaxxRider 4 | 5 | import asyncio 6 | import json 7 | import logging 8 | import os 9 | 10 | import pyrogram.types as pyrogram 11 | from tobrot import DEF_THUMB_NAIL_VID_S, LOGGER 12 | from tobrot.helper_funcs.display_progress import humanbytes 13 | 14 | 15 | async def extract_youtube_dl_formats( 16 | url, cf_name, yt_dl_user_name, yt_dl_pass_word, user_working_dir 17 | ): 18 | command_to_exec = [ 19 | "yt-dlp", 20 | "--no-warnings", 21 | "--youtube-skip-dash-manifest", 22 | "--no-check-certificate", 23 | "-j", 24 | url, 25 | ] 26 | if "hotstar" in url: 27 | command_to_exec.append("--geo-bypass-country") 28 | command_to_exec.append("IN") 29 | # 30 | if yt_dl_user_name is not None: 31 | command_to_exec.append("--username") 32 | command_to_exec.append(yt_dl_user_name) 33 | if yt_dl_pass_word is not None: 34 | command_to_exec.append("--password") 35 | command_to_exec.append(yt_dl_pass_word) 36 | 37 | LOGGER.info(command_to_exec) 38 | process = await asyncio.create_subprocess_exec( 39 | *command_to_exec, 40 | # stdout must a pipe to be accessible as process.stdout 41 | stdout=asyncio.subprocess.PIPE, 42 | stderr=asyncio.subprocess.PIPE, 43 | ) 44 | # Wait for the subprocess to finish 45 | stdout, stderr = await process.communicate() 46 | e_response = stderr.decode().strip() 47 | LOGGER.info(e_response) 48 | t_response = stdout.decode().strip() 49 | # LOGGER.info(t_response) 50 | # https://github.com/rg3/youtube-dl/issues/2630#issuecomment-38635239 51 | if e_response: 52 | # logger.warn("Status : FAIL", exc.returncode, exc.output) 53 | error_message = e_response.replace( 54 | "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.", 55 | "", 56 | ) 57 | return None, error_message, None 58 | if t_response: 59 | # logger.info(t_response) 60 | x_reponse = t_response 61 | response_json = [] 62 | if "\n" in x_reponse: 63 | for yu_r in x_reponse.split("\n"): 64 | response_json.append(json.loads(yu_r)) 65 | else: 66 | response_json.append(json.loads(x_reponse)) 67 | # response_json = json.loads(x_reponse) 68 | save_ytdl_json_path = user_working_dir + "/" + str("ytdleech") + ".json" 69 | with open(save_ytdl_json_path, "w", encoding="utf8") as outfile: 70 | json.dump(response_json, outfile, ensure_ascii=False) 71 | # logger.info(response_json) 72 | inline_keyboard = [] 73 | # 74 | thumb_image = DEF_THUMB_NAIL_VID_S 75 | # 76 | # LOGGER.info(response_json) 77 | for current_r_json in response_json: 78 | # 79 | thumb_image = current_r_json.get("thumbnail", thumb_image) 80 | # 81 | duration = None 82 | if "duration" in current_r_json: 83 | duration = current_r_json["duration"] 84 | if "formats" in current_r_json: 85 | for formats in current_r_json["formats"]: 86 | format_id = formats.get("format_id") 87 | format_string = formats.get("format_note") 88 | if format_string is None: 89 | format_string = formats.get("format") 90 | format_ext = formats.get("ext") 91 | approx_file_size = "" 92 | if "filesize" in formats: 93 | approx_file_size = humanbytes(formats["filesize"]) 94 | dipslay_str_uon = ( 95 | " " 96 | + format_string 97 | + " (" 98 | + format_ext.upper() 99 | + ") " 100 | + approx_file_size 101 | + " " 102 | ) 103 | cb_string_video = "{}|{}|{}".format("video", format_id, format_ext) 104 | ikeyboard = [] 105 | if "drive.google.com" in url: 106 | if format_id == "source": 107 | ikeyboard = [ 108 | pyrogram.InlineKeyboardButton( 109 | dipslay_str_uon, 110 | callback_data=(cb_string_video).encode("UTF-8"), 111 | ) 112 | ] 113 | else: 114 | if ( 115 | format_string is not None 116 | and not "audio only" in format_string 117 | ): 118 | ikeyboard = [ 119 | pyrogram.InlineKeyboardButton( 120 | dipslay_str_uon, 121 | callback_data=(cb_string_video).encode("UTF-8"), 122 | ) 123 | ] 124 | else: 125 | # special weird case :\ 126 | ikeyboard = [ 127 | pyrogram.InlineKeyboardButton( 128 | "SVideo [" + "] ( " + approx_file_size + " )", 129 | callback_data=(cb_string_video).encode("UTF-8"), 130 | ) 131 | ] 132 | inline_keyboard.append(ikeyboard) 133 | if duration is not None: 134 | cb_string_64 = "{}|{}|{}".format("audio", "64k", "mp3") 135 | cb_string_128 = "{}|{}|{}".format("audio", "128k", "mp3") 136 | cb_string = "{}|{}|{}".format("audio", "320k", "mp3") 137 | inline_keyboard.append( 138 | [ 139 | pyrogram.InlineKeyboardButton( 140 | "MP3 " + "(" + "64 kbps" + ")", 141 | callback_data=cb_string_64.encode("UTF-8"), 142 | ), 143 | pyrogram.InlineKeyboardButton( 144 | "MP3 " + "(" + "128 kbps" + ")", 145 | callback_data=cb_string_128.encode("UTF-8"), 146 | ), 147 | ] 148 | ) 149 | inline_keyboard.append( 150 | [ 151 | pyrogram.InlineKeyboardButton( 152 | "MP3 " + "(" + "320 kbps" + ")", 153 | callback_data=cb_string.encode("UTF-8"), 154 | ) 155 | ] 156 | ) 157 | else: 158 | format_id = current_r_json["format_id"] 159 | format_ext = current_r_json["ext"] 160 | cb_string_video = "{}|{}|{}".format("video", format_id, format_ext) 161 | inline_keyboard.append( 162 | [ 163 | pyrogram.InlineKeyboardButton( 164 | "SVideo", callback_data=(cb_string_video).encode("UTF-8") 165 | ) 166 | ] 167 | ) 168 | break 169 | reply_markup = pyrogram.InlineKeyboardMarkup(inline_keyboard) 170 | # LOGGER.info(reply_markup) 171 | if cf_name: 172 | succss_mesg = f"""Select the desired format | {cf_name}""" 173 | else: 174 | succss_mesg = f"""Select the desired format""" 175 | LOGGER.info(succss_mesg) 176 | return thumb_image, succss_mesg, reply_markup 177 | -------------------------------------------------------------------------------- /tobrot/__main__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | import io 6 | import logging 7 | import os 8 | import sys 9 | import traceback 10 | 11 | from pyrogram import Client, filters, idle 12 | from pyrogram.raw import functions, types 13 | from pyrogram.handlers import CallbackQueryHandler, MessageHandler 14 | 15 | from tobrot import app 16 | from tobrot import ( 17 | AUTH_CHANNEL, 18 | CANCEL_COMMAND_G, 19 | CLEAR_THUMBNAIL, 20 | CLONE_COMMAND_G, 21 | DOWNLOAD_LOCATION, 22 | GET_SIZE_G, 23 | GLEECH_COMMAND, 24 | GLEECH_UNZIP_COMMAND, 25 | GLEECH_ZIP_COMMAND, 26 | LEECH_COMMAND, 27 | LEECH_UNZIP_COMMAND, 28 | LEECH_ZIP_COMMAND, 29 | LOG_COMMAND, 30 | LOGGER, 31 | PYTDL_COMMAND, 32 | RENEWME_COMMAND, 33 | RENAME_COMMAND, 34 | SAVE_THUMBNAIL, 35 | STATUS_COMMAND, 36 | TELEGRAM_LEECH_UNZIP_COMMAND, 37 | TELEGRAM_LEECH_COMMAND, 38 | UPLOAD_COMMAND, 39 | YTDL_COMMAND, 40 | GYTDL_COMMAND, 41 | GPYTDL_COMMAND, 42 | TOGGLE_VID, 43 | RCLONE_COMMAND, 44 | TOGGLE_DOC, 45 | HELP_COMMAND 46 | ) 47 | from tobrot.helper_funcs.download import down_load_media_f 48 | from tobrot.plugins.call_back_button_handler import button 49 | # the logging things 50 | from tobrot.plugins.choose_rclone_config import rclone_command_f 51 | from tobrot.plugins.custom_thumbnail import clear_thumb_nail, save_thumb_nail 52 | from tobrot.plugins.incoming_message_fn import (g_clonee, g_yt_playlist, 53 | incoming_message_f, 54 | incoming_purge_message_f, 55 | incoming_youtube_dl_f, 56 | rename_tg_file) 57 | from tobrot.plugins.new_join_fn import help_message_f, new_join_f 58 | from tobrot.plugins.rclone_size import check_size_g, g_clearme 59 | from tobrot.plugins.status_message_fn import ( 60 | cancel_message_f, 61 | eval_message_f, 62 | exec_message_f, 63 | status_message_f, 64 | upload_document_f, 65 | upload_log_file, 66 | upload_as_doc, 67 | upload_as_video 68 | ) 69 | 70 | if __name__ == "__main__": 71 | # create download directory, if not exist 72 | if not os.path.isdir(DOWNLOAD_LOCATION): 73 | os.makedirs(DOWNLOAD_LOCATION) 74 | # Starting The Bot 75 | app.start() 76 | ############################################################################## 77 | incoming_message_handler = MessageHandler( 78 | incoming_message_f, 79 | filters=filters.command( 80 | [ 81 | LEECH_COMMAND, 82 | LEECH_UNZIP_COMMAND, 83 | LEECH_ZIP_COMMAND, 84 | GLEECH_COMMAND, 85 | GLEECH_UNZIP_COMMAND, 86 | GLEECH_ZIP_COMMAND, 87 | ] 88 | ) 89 | & filters.chat(chats=AUTH_CHANNEL), 90 | ) 91 | app.add_handler(incoming_message_handler) 92 | ############################################################################## 93 | incoming_telegram_download_handler = MessageHandler( 94 | down_load_media_f, 95 | filters=filters.command([TELEGRAM_LEECH_COMMAND, TELEGRAM_LEECH_UNZIP_COMMAND]) 96 | & filters.chat(chats=AUTH_CHANNEL), 97 | ) 98 | app.add_handler(incoming_telegram_download_handler) 99 | ############################################################################## 100 | incoming_purge_message_handler = MessageHandler( 101 | incoming_purge_message_f, 102 | filters=filters.command(["purge"]) & filters.chat(chats=AUTH_CHANNEL), 103 | ) 104 | app.add_handler(incoming_purge_message_handler) 105 | ############################################################################## 106 | incoming_clone_handler = MessageHandler( 107 | g_clonee, 108 | filters=filters.command([f"{CLONE_COMMAND_G}"]) 109 | & filters.chat(chats=AUTH_CHANNEL), 110 | ) 111 | app.add_handler(incoming_clone_handler) 112 | ############################################################################## 113 | incoming_size_checker_handler = MessageHandler( 114 | check_size_g, 115 | filters=filters.command([f"{GET_SIZE_G}"]) & filters.chat(chats=AUTH_CHANNEL), 116 | ) 117 | app.add_handler(incoming_size_checker_handler) 118 | ############################################################################## 119 | incoming_g_clear_handler = MessageHandler( 120 | g_clearme, 121 | filters=filters.command([f"{RENEWME_COMMAND}"]) 122 | & filters.chat(chats=AUTH_CHANNEL), 123 | ) 124 | app.add_handler(incoming_g_clear_handler) 125 | ############################################################################## 126 | incoming_youtube_dl_handler = MessageHandler( 127 | incoming_youtube_dl_f, 128 | filters=filters.command([YTDL_COMMAND, GYTDL_COMMAND]) 129 | & filters.chat(chats=AUTH_CHANNEL), 130 | ) 131 | app.add_handler(incoming_youtube_dl_handler) 132 | ############################################################################## 133 | incoming_youtube_playlist_dl_handler = MessageHandler( 134 | g_yt_playlist, 135 | filters=filters.command([PYTDL_COMMAND, GPYTDL_COMMAND]) 136 | & filters.chat(chats=AUTH_CHANNEL), 137 | ) 138 | app.add_handler(incoming_youtube_playlist_dl_handler) 139 | ############################################################################## 140 | status_message_handler = MessageHandler( 141 | status_message_f, 142 | filters=filters.command([f"{STATUS_COMMAND}"]) 143 | & filters.chat(chats=AUTH_CHANNEL), 144 | ) 145 | app.add_handler(status_message_handler) 146 | ############################################################################## 147 | cancel_message_handler = MessageHandler( 148 | cancel_message_f, 149 | filters=filters.command([f"{CANCEL_COMMAND_G}"]) 150 | & filters.chat(chats=AUTH_CHANNEL), 151 | ) 152 | app.add_handler(cancel_message_handler) 153 | ############################################################################## 154 | exec_message_handler = MessageHandler( 155 | exec_message_f, 156 | filters=filters.command(["exec"]) & filters.chat(chats=AUTH_CHANNEL), 157 | ) 158 | app.add_handler(exec_message_handler) 159 | ############################################################################## 160 | eval_message_handler = MessageHandler( 161 | eval_message_f, 162 | filters=filters.command(["eval"]) & filters.chat(chats=AUTH_CHANNEL), 163 | ) 164 | app.add_handler(eval_message_handler) 165 | ############################################################################## 166 | rename_message_handler = MessageHandler( 167 | rename_tg_file, 168 | filters=filters.command([f"{RENAME_COMMAND}"]) & filters.chat(chats=AUTH_CHANNEL), 169 | ) 170 | app.add_handler(rename_message_handler) 171 | ############################################################################## 172 | upload_document_handler = MessageHandler( 173 | upload_document_f, 174 | filters=filters.command([f"{UPLOAD_COMMAND}"]) 175 | & filters.chat(chats=AUTH_CHANNEL), 176 | ) 177 | app.add_handler(upload_document_handler) 178 | ############################################################################## 179 | upload_log_handler = MessageHandler( 180 | upload_log_file, 181 | filters=filters.command([f"{LOG_COMMAND}"]) & filters.chat(chats=AUTH_CHANNEL), 182 | ) 183 | app.add_handler(upload_log_handler) 184 | ############################################################################## 185 | help_text_handler = MessageHandler( 186 | help_message_f, 187 | filters=filters.command([f"{HELP_COMMAND}"]) & filters.chat(chats=AUTH_CHANNEL), 188 | ) 189 | app.add_handler(help_text_handler) 190 | ############################################################################## 191 | new_join_handler = MessageHandler( 192 | new_join_f, filters=~filters.chat(chats=AUTH_CHANNEL) 193 | ) 194 | app.add_handler(new_join_handler) 195 | ############################################################################## 196 | ''' 197 | group_new_join_handler = MessageHandler( 198 | help_message_f, 199 | filters=filters.chat(chats=AUTH_CHANNEL) & filters.new_chat_members, 200 | ) 201 | app.add_handler(group_new_join_handler) 202 | ''' 203 | ############################################################################## 204 | call_back_button_handler = CallbackQueryHandler(button) 205 | app.add_handler(call_back_button_handler) 206 | ############################################################################## 207 | save_thumb_nail_handler = MessageHandler( 208 | save_thumb_nail, 209 | filters=filters.command([f"{SAVE_THUMBNAIL}"]) 210 | & filters.chat(chats=AUTH_CHANNEL), 211 | ) 212 | app.add_handler(save_thumb_nail_handler) 213 | ############################################################################## 214 | clear_thumb_nail_handler = MessageHandler( 215 | clear_thumb_nail, 216 | filters=filters.command([f"{CLEAR_THUMBNAIL}"]) 217 | & filters.chat(chats=AUTH_CHANNEL), 218 | ) 219 | app.add_handler(clear_thumb_nail_handler) 220 | ############################################################################## 221 | rclone_config_handler = MessageHandler( 222 | rclone_command_f, filters=filters.command([f"{RCLONE_COMMAND}"]) 223 | ) 224 | app.add_handler(rclone_config_handler) 225 | ############################################################################## 226 | upload_as_doc_handler = MessageHandler( 227 | upload_as_doc, 228 | filters=filters.command([f"{TOGGLE_DOC}"]) 229 | & filters.chat(chats=AUTH_CHANNEL), 230 | ) 231 | app.add_handler(upload_as_doc_handler) 232 | ############################################################################## 233 | upload_as_video_handler = MessageHandler( 234 | upload_as_video, 235 | filters=filters.command([f"{TOGGLE_VID}"]) 236 | & filters.chat(chats=AUTH_CHANNEL), 237 | ) 238 | app.add_handler(upload_as_video_handler) 239 | ############################################################################## 240 | 241 | logging.info(f"@{(app.get_me()).username} Has Started Running...🏃💨💨 Now gimme 100$ 🐸") 242 | 243 | idle() 244 | 245 | app.stop() 246 | -------------------------------------------------------------------------------- /tobrot/plugins/status_message_fn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | import asyncio 6 | import io 7 | import logging 8 | import os 9 | import shutil 10 | import sys 11 | import time 12 | import traceback 13 | 14 | import psutil 15 | import math 16 | from pyrogram.errors import FloodWait, MessageIdInvalid, MessageNotModified 17 | from tobrot.helper_funcs.admin_check import AdminCheck 18 | 19 | from tobrot import ( 20 | AUTH_CHANNEL, 21 | BOT_START_TIME, 22 | LOGGER, 23 | MAX_MESSAGE_LENGTH, 24 | user_specific_config, 25 | gid_dict, 26 | _lock, 27 | EDIT_SLEEP_TIME_OUT, 28 | FINISHED_PROGRESS_STR, 29 | UN_FINISHED_PROGRESS_STR 30 | ) 31 | 32 | 33 | # the logging things 34 | from tobrot.helper_funcs.display_progress import TimeFormatter, humanbytes 35 | from tobrot.helper_funcs.download_aria_p_n import (aria_start, 36 | call_apropriate_function) 37 | from tobrot.helper_funcs.upload_to_tg import upload_to_tg 38 | from tobrot.UserDynaConfig import UserDynaConfig 39 | 40 | 41 | async def upload_as_doc(client, message): 42 | user_specific_config[message.from_user.id]=UserDynaConfig(message.from_user.id,True) 43 | await message.reply_text("**🗞 Your Files Will Be Uploaded As Document 📁**") 44 | 45 | 46 | async def upload_as_video(client, message): 47 | user_specific_config[message.from_user.id]=UserDynaConfig(message.from_user.id,False) 48 | await message.reply_text("**🗞 Your Files Will Be Uploaded As Streamable 🎞**") 49 | 50 | 51 | async def status_message_f( 52 | client, message 53 | ): # weird code but 'This is the way' @gautamajay52 54 | aria_i_p = await aria_start() 55 | # Show All Downloads 56 | to_edit = await message.reply(".......") 57 | chat_id = int(message.chat.id) 58 | mess_id = int(to_edit.message_id) 59 | async with _lock: 60 | if len(gid_dict[chat_id]) == 0: 61 | gid_dict[chat_id].append(mess_id) 62 | else: 63 | if not mess_id in gid_dict[chat_id]: 64 | await client.delete_messages(chat_id, gid_dict[chat_id]) 65 | gid_dict[chat_id].pop() 66 | gid_dict[chat_id].append(mess_id) 67 | 68 | prev_mess = "By gautamajay52" 69 | await message.delete() 70 | while True: 71 | downloads = aria_i_p.get_downloads() 72 | msg = "" 73 | for file in downloads: 74 | downloading_dir_name = "NA" 75 | try: 76 | downloading_dir_name = str(file.name) 77 | except: 78 | pass 79 | if file.status == "active": 80 | is_file = file.seeder 81 | if is_file is None: 82 | msgg = f"Conn: {file.connections}" 83 | else: 84 | msgg = f"Peers: {file.connections} | Seeders: {file.num_seeders}" 85 | 86 | percentage = int(file.progress_string(0).split('%')[0]) 87 | prog = "[{0}{1}]".format("".join([FINISHED_PROGRESS_STR for i in range(math.floor(percentage / 5))]),"".join([UN_FINISHED_PROGRESS_STR for i in range(20 - math.floor(percentage / 5))])) 88 | msg += f"════════════════════════════════\n" 89 | msg += f"\n{downloading_dir_name}" 90 | msg += f"\n{prog}" 91 | msg += f"\nSpeed: {file.download_speed_string()}" 92 | msg += f"\nStatus: {file.progress_string()} of {file.total_length_string()}" 93 | msg += f"\nETA: {file.eta_string()}" 94 | msg += f"\n{msgg}" 95 | msg += f"\nTo Cancel: /cancel {file.gid}" 96 | msg += "\n" 97 | 98 | hr, mi, se = up_time(time.time() - BOT_START_TIME) 99 | total, used, free = shutil.disk_usage(".") 100 | ram = psutil.virtual_memory().percent 101 | cpu = psutil.cpu_percent() 102 | total = humanbytes(total) 103 | used = humanbytes(used) 104 | free = humanbytes(free) 105 | 106 | ms_g = ( 107 | f"Bot Uptime: {hr} : {mi} : {se}\n" 108 | f"T: {total} U: {used} F: {free}\n" 109 | f"RAM: {ram}% CPU: {cpu}%\n" 110 | ) 111 | if msg == "": 112 | msg = "🤷‍♂️ No Active, Queued or Paused TORRENTs" 113 | msg = ms_g + "\n" + msg 114 | await to_edit.edit(msg) 115 | break 116 | msg = msg + "\n" + ms_g 117 | if len(msg) > MAX_MESSAGE_LENGTH: # todo - will catch later 118 | with io.BytesIO(str.encode(msg)) as out_file: 119 | out_file.name = "status.text" 120 | await client.send_document( 121 | chat_id=message.chat.id, 122 | document=out_file, 123 | ) 124 | break 125 | else: 126 | if msg != prev_mess: 127 | try: 128 | await to_edit.edit(msg, parse_mode="html") 129 | except MessageIdInvalid as df: 130 | break 131 | except MessageNotModified as ep: 132 | LOGGER.info(ep) 133 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 134 | except FloodWait as e: 135 | LOGGER.info(e) 136 | time.sleep(e.x) 137 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 138 | prev_mess = msg 139 | 140 | 141 | async def cancel_message_f(client, message): 142 | if len(message.command) > 1: 143 | # /cancel command 144 | i_m_s_e_g = await message.reply_text("checking..?", quote=True) 145 | aria_i_p = await aria_start() 146 | g_id = message.command[1].strip() 147 | LOGGER.info(g_id) 148 | try: 149 | downloads = aria_i_p.get_download(g_id) 150 | name = downloads.name 151 | size = downloads.total_length_string() 152 | gid_list = downloads.followed_by_ids 153 | downloads = [downloads] 154 | if len(gid_list) != 0: 155 | downloads = aria_i_p.get_downloads(gid_list) 156 | aria_i_p.remove(downloads=downloads, force=True, files=True, clean=True) 157 | await i_m_s_e_g.edit_text( 158 | f"Download cancelled :\n{name} ({size}) by {message.from_user.first_name}" 159 | ) 160 | except Exception as e: 161 | await i_m_s_e_g.edit_text("FAILED\n\n" + str(e) + "\n#error") 162 | else: 163 | await message.delete() 164 | 165 | 166 | async def exec_message_f(client, message): 167 | if message.from_user.id in AUTH_CHANNEL: 168 | DELAY_BETWEEN_EDITS = 0.3 169 | PROCESS_RUN_TIME = 100 170 | cmd = message.text.split(" ", maxsplit=1)[1] 171 | 172 | reply_to_id = message.message_id 173 | if message.reply_to_message: 174 | reply_to_id = message.reply_to_message.message_id 175 | 176 | start_time = time.time() + PROCESS_RUN_TIME 177 | process = await asyncio.create_subprocess_shell( 178 | cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 179 | ) 180 | stdout, stderr = await process.communicate() 181 | e = stderr.decode() 182 | if not e: 183 | e = "No Error" 184 | o = stdout.decode() 185 | if not o: 186 | o = "No Output" 187 | else: 188 | _o = o.split("\n") 189 | o = "`\n".join(_o) 190 | OUTPUT = f"**QUERY:**\n__Command:__\n`{cmd}` \n__PID:__\n`{process.pid}`\n\n**stderr:** \n`{e}`\n**Output:**\n{o}" 191 | 192 | if len(OUTPUT) > MAX_MESSAGE_LENGTH: 193 | with io.BytesIO(str.encode(OUTPUT)) as out_file: 194 | out_file.name = "exec.text" 195 | await client.send_document( 196 | chat_id=message.chat.id, 197 | document=out_file, 198 | caption=cmd, 199 | disable_notification=True, 200 | reply_to_message_id=reply_to_id, 201 | ) 202 | await message.delete() 203 | else: 204 | await message.reply_text(OUTPUT) 205 | 206 | 207 | async def upload_document_f(client, message): 208 | imsegd = await message.reply_text("processing ...") 209 | if message.from_user.id in AUTH_CHANNEL: 210 | if " " in message.text: 211 | recvd_command, local_file_name = message.text.split(" ", 1) 212 | recvd_response = await upload_to_tg( 213 | imsegd, local_file_name, message.from_user.id, {}, client 214 | ) 215 | LOGGER.info(recvd_response) 216 | await imsegd.delete() 217 | 218 | 219 | async def eval_message_f(client, message): 220 | if message.from_user.id in AUTH_CHANNEL: 221 | status_message = await message.reply_text("Processing ...") 222 | cmd = message.text.split(" ", maxsplit=1)[1] 223 | 224 | reply_to_id = message.message_id 225 | if message.reply_to_message: 226 | reply_to_id = message.reply_to_message.message_id 227 | 228 | old_stderr = sys.stderr 229 | old_stdout = sys.stdout 230 | redirected_output = sys.stdout = io.StringIO() 231 | redirected_error = sys.stderr = io.StringIO() 232 | stdout, stderr, exc = None, None, None 233 | 234 | try: 235 | await aexec(cmd, client, message) 236 | except Exception: 237 | exc = traceback.format_exc() 238 | 239 | stdout = redirected_output.getvalue() 240 | stderr = redirected_error.getvalue() 241 | sys.stdout = old_stdout 242 | sys.stderr = old_stderr 243 | 244 | evaluation = "" 245 | if exc: 246 | evaluation = exc 247 | elif stderr: 248 | evaluation = stderr 249 | elif stdout: 250 | evaluation = stdout 251 | else: 252 | evaluation = "Success" 253 | 254 | final_output = ( 255 | "EVAL: {}\n\nOUTPUT:\n{} \n".format( 256 | cmd, evaluation.strip() 257 | ) 258 | ) 259 | 260 | if len(final_output) > MAX_MESSAGE_LENGTH: 261 | with open("eval.text", "w+", encoding="utf8") as out_file: 262 | out_file.write(str(final_output)) 263 | await message.reply_document( 264 | document="eval.text", 265 | caption=cmd, 266 | disable_notification=True, 267 | reply_to_message_id=reply_to_id, 268 | ) 269 | os.remove("eval.text") 270 | await status_message.delete() 271 | else: 272 | await status_message.edit(final_output) 273 | 274 | 275 | async def aexec(code, client, message): 276 | exec( 277 | f"async def __aexec(client, message): " 278 | + "".join(f"\n {l}" for l in code.split("\n")) 279 | ) 280 | return await locals()["__aexec"](client, message) 281 | 282 | 283 | def up_time(time_taken): 284 | hours, _hour = divmod(time_taken, 3600) 285 | minutes, seconds = divmod(_hour, 60) 286 | return round(hours), round(minutes), round(seconds) 287 | 288 | 289 | async def upload_log_file(client, message): 290 | g = await AdminCheck(client, message.chat.id, message.from_user.id) 291 | if g: 292 | await message.reply_document("Torrentleech-Gdrive.txt") -------------------------------------------------------------------------------- /tobrot/plugins/incoming_message_fn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 | MaxxRider 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import time 9 | from pathlib import Path 10 | import aria2p 11 | import requests 12 | from tobrot import ( 13 | DOWNLOAD_LOCATION, 14 | GLEECH_COMMAND, 15 | GLEECH_UNZIP_COMMAND, 16 | GLEECH_ZIP_COMMAND, 17 | LEECH_COMMAND, 18 | LEECH_UNZIP_COMMAND, 19 | LEECH_ZIP_COMMAND, 20 | LOGGER, 21 | YTDL_COMMAND, 22 | GPYTDL_COMMAND, 23 | PYTDL_COMMAND, 24 | ) 25 | from tobrot.helper_funcs.admin_check import AdminCheck 26 | from tobrot.helper_funcs.cloneHelper import CloneHelper 27 | from tobrot.helper_funcs.download import download_tg 28 | from tobrot.helper_funcs.download_aria_p_n import ( 29 | aria_start, 30 | call_apropriate_function, 31 | ) 32 | from tobrot.helper_funcs.download_from_link import request_download 33 | from tobrot.helper_funcs.extract_link_from_message import extract_link 34 | from tobrot.helper_funcs.upload_to_tg import upload_to_tg 35 | from tobrot.helper_funcs.youtube_dl_extractor import extract_youtube_dl_formats 36 | from tobrot.helper_funcs.ytplaylist import yt_playlist_downg 37 | 38 | 39 | async def incoming_purge_message_f(client, message): 40 | """/purge command""" 41 | print(message.client) 42 | i_m_sefg2 = await message.reply_text("Purging...", quote=True) 43 | if await AdminCheck(client, message.chat.id, message.from_user.id): 44 | aria_i_p = await aria_start() 45 | # Show All Downloads 46 | downloads = aria_i_p.get_downloads() 47 | for download in downloads: 48 | LOGGER.info(download.remove(force=True)) 49 | await i_m_sefg2.delete() 50 | 51 | 52 | async def incoming_message_f(client, message): 53 | """/leech command or /gleech command""" 54 | user_command = message.command[0] 55 | g_id = message.from_user.id 56 | # get link from the incoming message 57 | i_m_sefg = await message.reply_text("Processing...", quote=True) 58 | rep_mess = message.reply_to_message 59 | is_file = False 60 | dl_url = '' 61 | cf_name = '' 62 | if rep_mess: 63 | file_name = '' 64 | if rep_mess.media: 65 | file = [rep_mess.document, rep_mess.video, rep_mess.audio] 66 | file_name = [fi for fi in file if fi is not None][0].file_name 67 | if not rep_mess.media or str(file_name).lower().endswith(".torrent"): 68 | dl_url, cf_name, _, _ = await extract_link(message.reply_to_message, "LEECH") 69 | LOGGER.info(dl_url) 70 | LOGGER.info(cf_name) 71 | else: 72 | if user_command == LEECH_COMMAND.lower(): 73 | await i_m_sefg.edit("No download source provided 🙄") 74 | return 75 | is_file = True 76 | dl_url = rep_mess 77 | elif len(message.command) == 2: 78 | dl_url = message.command[1] 79 | LOGGER.info(dl_url) 80 | 81 | else: 82 | await i_m_sefg.edit("Hey Dude !\n\n 🐈 Reply with Direct /Torrent Link") 83 | return 84 | if dl_url is not None: 85 | 86 | current_user_id = message.from_user.id 87 | # create an unique directory 88 | new_download_location = os.path.join( 89 | DOWNLOAD_LOCATION, str(current_user_id), str(time.time()) 90 | ) 91 | # create download directory, if not exist 92 | if not os.path.isdir(new_download_location): 93 | os.makedirs(new_download_location) 94 | aria_i_p = '' 95 | if not is_file: 96 | await i_m_sefg.edit_text("Extracting links...") 97 | # start the aria2c daemon 98 | aria_i_p = await aria_start() 99 | # LOGGER.info(aria_i_p) 100 | 101 | await i_m_sefg.edit_text("Added to downloads. Send /status") 102 | # try to download the "link" 103 | is_zip = False 104 | is_cloud = False 105 | is_unzip = False 106 | 107 | if user_command == LEECH_UNZIP_COMMAND.lower(): 108 | is_unzip = True 109 | elif user_command == LEECH_ZIP_COMMAND.lower(): 110 | is_zip = True 111 | 112 | if user_command == GLEECH_COMMAND.lower(): 113 | is_cloud = True 114 | if user_command == GLEECH_UNZIP_COMMAND.lower(): 115 | is_cloud = True 116 | is_unzip = True 117 | elif user_command == GLEECH_ZIP_COMMAND.lower(): 118 | is_cloud = True 119 | is_zip = True 120 | sagtus, err_message = await call_apropriate_function( 121 | aria_i_p, 122 | dl_url, 123 | new_download_location, 124 | i_m_sefg, 125 | is_zip, 126 | cf_name, 127 | is_cloud, 128 | is_unzip, 129 | is_file, 130 | message, 131 | client, 132 | ) 133 | if not sagtus: 134 | # if FAILED, display the error message 135 | await i_m_sefg.edit_text(err_message) 136 | else: 137 | await i_m_sefg.edit_text( 138 | f"**FCUK**! wat have you entered. \nAPI Error: {cf_name}" 139 | ) 140 | 141 | 142 | async def incoming_youtube_dl_f(client, message): 143 | """ /ytdl command """ 144 | current_user_id = message.from_user.id 145 | 146 | i_m_sefg = await message.reply_text("Prrocessing...🔃", quote=True) 147 | # LOGGER.info(message) 148 | # extract link from message 149 | if message.reply_to_message: 150 | dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word = await extract_link( 151 | message.reply_to_message, "YTDL" 152 | ) 153 | LOGGER.info(dl_url) 154 | LOGGER.info(cf_name) 155 | elif len(message.command) == 2: 156 | dl_url = message.command[1] 157 | LOGGER.info(dl_url) 158 | cf_name = None 159 | yt_dl_user_name = None 160 | yt_dl_pass_word = None 161 | cf_name = None 162 | else: 163 | await i_m_sefg.edit("🐈 Oops Reply To YTDL Supported Link.") 164 | return 165 | if dl_url is not None: 166 | await i_m_sefg.edit_text("Getting Available Formate...") 167 | # create an unique directory 168 | user_working_dir = os.path.join(DOWNLOAD_LOCATION, str(current_user_id)) 169 | # create download directory, if not exist 170 | if not os.path.isdir(user_working_dir): 171 | os.makedirs(user_working_dir) 172 | # list the formats, and display in button markup formats 173 | thumb_image, text_message, reply_markup = await extract_youtube_dl_formats( 174 | dl_url, cf_name, yt_dl_user_name, yt_dl_pass_word, user_working_dir 175 | ) 176 | if thumb_image is not None: 177 | req = requests.get(f"{thumb_image}") 178 | thumb_img = f"{current_user_id}.jpg" 179 | with open(thumb_img, "wb") as thumb: 180 | thumb.write(req.content) 181 | await message.reply_photo( 182 | # text_message, 183 | photo=thumb_img, 184 | quote=True, 185 | caption=text_message, 186 | reply_markup=reply_markup, 187 | ) 188 | await i_m_sefg.delete() 189 | else: 190 | await i_m_sefg.edit_text(text=text_message, reply_markup=reply_markup) 191 | else: 192 | await i_m_sefg.edit_text( 193 | "**FCUK**! wat have you entered.\n" 194 | f"API Error: {cf_name}" 195 | ) 196 | 197 | 198 | # playlist 199 | async def g_yt_playlist(client, message): 200 | """ /pytdl command """ 201 | user_command = message.command[0] 202 | usr_id = message.from_user.id 203 | is_cloud = False 204 | url = None 205 | if message.reply_to_message: 206 | url = message.reply_to_message.text 207 | if user_command == GPYTDL_COMMAND.lower(): 208 | is_cloud = True 209 | elif len(message.command) == 2: 210 | url = message.command[1] 211 | if user_command == GPYTDL_COMMAND.lower(): 212 | is_cloud = True 213 | else: 214 | await message.reply_text(" Reply with Youtube Playlist link", quote=True) 215 | return 216 | if "youtube.com/playlist" in url: 217 | u_men = message.from_user.mention 218 | i_m_sefg = await message.reply_text( 219 | f"Ok Fine 🐈 {u_men} Bro!!:\n Your Request has been ADDED\n\n Please wait until Upload", 220 | parse_mode="html", 221 | ) 222 | await yt_playlist_downg(message, i_m_sefg, client, is_cloud) 223 | 224 | else: 225 | await message.reply_text("YouTube playlist link only 🙄", quote=True) 226 | 227 | # 228 | 229 | 230 | async def g_clonee(client, message): 231 | """ /gclone command """ 232 | g_id = message.from_user.id 233 | if message.reply_to_message is not None: 234 | LOGGER.info(message.reply_to_message.text) 235 | gclone = CloneHelper(message) 236 | gclone.config() 237 | a, h = gclone.get_id() 238 | LOGGER.info(a) 239 | LOGGER.info(h) 240 | await gclone.gcl() 241 | await gclone.link_gen_size() 242 | else: 243 | await message.reply_text( 244 | "You should reply to a message, which format should be [ID of Gdrive file/folder Name of the file/folder]\nOr read Github for detailled information" 245 | ) 246 | 247 | 248 | async def rename_tg_file(client, message): 249 | usr_id = message.from_user.id 250 | if not message.reply_to_message: 251 | await message.reply("Reply with Telegram Media None", quote=True) 252 | return 253 | if len(message.command) > 1: 254 | new_name = ( 255 | str(Path().resolve()) + "/" + 256 | message.text.split(" ", maxsplit=1)[1].strip() 257 | ) 258 | file, mess_age = await download_tg(client, message) 259 | try: 260 | if file: 261 | os.rename(file, new_name) 262 | else: 263 | return 264 | except Exception as g_g: 265 | LOGGER.error(g_g) 266 | await message.reply_text("g_g") 267 | response = {} 268 | final_response = await upload_to_tg( 269 | mess_age, new_name, usr_id, response, client 270 | ) 271 | LOGGER.info(final_response) 272 | if not final_response: 273 | return 274 | try: 275 | message_to_send = "" 276 | for key_f_res_se in final_response: 277 | local_file_name = key_f_res_se 278 | message_id = final_response[key_f_res_se] 279 | channel_id = str(message.chat.id)[4:] 280 | private_link = f"https://t.me/c/{channel_id}/{message_id}" 281 | message_to_send += "➪ " 284 | message_to_send += local_file_name 285 | message_to_send += "" 286 | message_to_send += "\n" 287 | if message_to_send != "": 288 | mention_req_user = ( 289 | f"🐈 Hey Bru!! Your Requested Files 👇\n\n" 290 | ) 291 | message_to_send = mention_req_user + message_to_send 292 | message_to_send = message_to_send + "\n\n" + " #UPLOADS\n\n💫 Powered By : @TGFilmZone" 293 | else: 294 | message_to_send = "FAILED to upload files. 😞😞" 295 | await message.reply_text( 296 | text=message_to_send, quote=True, disable_web_page_preview=True 297 | ) 298 | except Exception as pe: 299 | LOGGER.info(pe) 300 | 301 | else: 302 | await message.reply_text( 303 | " Oops 😬\n\nProvide Name with extension\n\n➩Example: /rename Avengers Endgame.mkv", quote=True 304 | ) 305 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/download_aria_p_n.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 | MaxxRider 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import sys 9 | import time 10 | import requests 11 | import re 12 | from re import search 13 | import subprocess 14 | import hashlib 15 | import math 16 | 17 | import aria2p 18 | from pyrogram.errors import FloodWait, MessageNotModified 19 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message 20 | from tobrot import ( 21 | ARIA_TWO_STARTED_PORT, 22 | AUTH_CHANNEL, 23 | CUSTOM_FILE_NAME, 24 | DOWNLOAD_LOCATION, 25 | EDIT_SLEEP_TIME_OUT, 26 | LOGGER, 27 | MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START, 28 | ) 29 | from tobrot.helper_funcs.create_compressed_archive import ( 30 | create_archive, 31 | get_base_name, 32 | unzip_me, 33 | ) 34 | from tobrot.helper_funcs.extract_link_from_message import extract_link 35 | from tobrot.helper_funcs.upload_to_tg import upload_to_gdrive, upload_to_tg 36 | from tobrot.helper_funcs.download import download_tg 37 | 38 | from tobrot.helper_funcs.direct_link_generator import direct_link_generator 39 | from tobrot.helper_funcs.exceptions import DirectDownloadLinkException 40 | 41 | sys.setrecursionlimit(10 ** 4) 42 | 43 | 44 | async def aria_start(): 45 | aria2_daemon_start_cmd = [] 46 | # start the daemon, aria2c command 47 | aria2_daemon_start_cmd.append("aria2c") 48 | aria2_daemon_start_cmd.append("--conf-path=/app/tobrot/aria2/aria2.conf") 49 | aria2_daemon_start_cmd.append("--allow-overwrite=true") 50 | aria2_daemon_start_cmd.append("--daemon=true") 51 | # aria2_daemon_start_cmd.append(f"--dir={DOWNLOAD_LOCATION}") 52 | # TODO: this does not work, need to investigate this. 53 | # but for now, https://t.me/TrollVoiceBot?start=858 54 | aria2_daemon_start_cmd.append("--enable-rpc") 55 | aria2_daemon_start_cmd.append("--disk-cache=0") 56 | aria2_daemon_start_cmd.append("--follow-torrent=mem") 57 | aria2_daemon_start_cmd.append("--max-connection-per-server=16") 58 | aria2_daemon_start_cmd.append("--min-split-size=10M") 59 | aria2_daemon_start_cmd.append("--rpc-listen-all=false") 60 | aria2_daemon_start_cmd.append(f"--rpc-listen-port={ARIA_TWO_STARTED_PORT}") 61 | aria2_daemon_start_cmd.append("--rpc-max-request-size=1024M") 62 | aria2_daemon_start_cmd.append("--seed-ratio=0.01") 63 | aria2_daemon_start_cmd.append("--seed-time=1") 64 | aria2_daemon_start_cmd.append("--max-overall-upload-limit=2M") 65 | aria2_daemon_start_cmd.append("--split=16") 66 | aria2_daemon_start_cmd.append(f"--bt-stop-timeout={MAX_TIME_TO_WAIT_FOR_TORRENTS_TO_START}") 67 | # 68 | LOGGER.info(aria2_daemon_start_cmd) 69 | # 70 | process = await asyncio.create_subprocess_exec( 71 | *aria2_daemon_start_cmd, 72 | stdout=asyncio.subprocess.PIPE, 73 | stderr=asyncio.subprocess.PIPE, 74 | ) 75 | stdout, stderr = await process.communicate() 76 | 77 | aria2 = aria2p.API( 78 | aria2p.Client(host="http://localhost", 79 | port=ARIA_TWO_STARTED_PORT, secret="") 80 | ) 81 | return aria2 82 | 83 | 84 | def add_magnet(aria_instance, magnetic_link, c_file_name): 85 | options = None 86 | # if c_file_name is not None: 87 | # options = { 88 | # "dir": c_file_name 89 | # } 90 | try: 91 | download = aria_instance.add_magnet(magnetic_link, options=options) 92 | except Exception as e: 93 | return ( 94 | False, 95 | "**FAILED** \n" + str(e) + " \n Your link is Dead 🐈", 96 | ) 97 | else: 98 | return True, "" + download.gid + "" 99 | 100 | 101 | def add_torrent(aria_instance, torrent_file_path): 102 | if torrent_file_path is None: 103 | return ( 104 | False, 105 | "**FAILED** \n" 106 | + str(e) 107 | + " \nsomething wrongings when trying to add TORRENT file", 108 | ) 109 | if os.path.exists(torrent_file_path): 110 | # Add Torrent Into Queue 111 | try: 112 | download = aria_instance.add_torrent( 113 | torrent_file_path, uris=None, options=None, position=None 114 | ) 115 | except Exception as e: 116 | return ( 117 | False, 118 | "**FAILED** \n" 119 | + str(e) 120 | + " \n Your Link is Slow Dude 🐈", 121 | ) 122 | else: 123 | return True, "" + download.gid + "" 124 | else: 125 | return False, "**FAILED** \nPlease try other sources to get workable link" 126 | 127 | 128 | def add_url(aria_instance, text_url, c_file_name): 129 | options = None 130 | # if c_file_name is not None: 131 | # options = { 132 | # "dir": c_file_name 133 | # } 134 | if "zippyshare.com" in text_url \ 135 | or "osdn.net" in text_url \ 136 | or "mediafire.com" in text_url \ 137 | or "cloud.mail.ru" in text_url \ 138 | or "github.com" in text_url \ 139 | or "yadi.sk" in text_url \ 140 | or "racaty.net" in text_url: 141 | try: 142 | urisitring = direct_link_generator(text_url) 143 | uris = [urisitring] 144 | except DirectDownloadLinkException as e: 145 | LOGGER.info(f'{text_url}: {e}') 146 | else: 147 | uris = [text_url] 148 | # Add URL Into Queue 149 | try: 150 | download = aria_instance.add_uris(uris, options=options) 151 | except Exception as e: 152 | return ( 153 | False, 154 | "**FAILED** \n" + 155 | str(e) + " \nPlease do not send SLOW links. Read /help", 156 | ) 157 | else: 158 | return True, "" + download.gid + "" 159 | 160 | 161 | async def call_apropriate_function( 162 | aria_instance, 163 | incoming_link, 164 | c_file_name, 165 | sent_message_to_update_tg_p, 166 | is_zip, 167 | cstom_file_name, 168 | is_cloud, 169 | is_unzip, 170 | is_file, 171 | user_message, 172 | client, 173 | ): 174 | if not is_file: 175 | if incoming_link.lower().startswith("magnet:"): 176 | sagtus, err_message = add_magnet( 177 | aria_instance, incoming_link, c_file_name) 178 | elif incoming_link.lower().endswith(".torrent"): 179 | sagtus, err_message = add_torrent(aria_instance, incoming_link) 180 | else: 181 | sagtus, err_message = add_url( 182 | aria_instance, incoming_link, c_file_name) 183 | if not sagtus: 184 | return sagtus, err_message 185 | LOGGER.info(err_message) 186 | # https://stackoverflow.com/a/58213653/4723940 187 | await check_progress_for_dl( 188 | aria_instance, err_message, sent_message_to_update_tg_p, None 189 | ) 190 | if incoming_link.startswith("magnet:"): 191 | # 192 | err_message = await check_metadata(aria_instance, err_message) 193 | # 194 | await asyncio.sleep(1) 195 | if err_message is not None: 196 | await check_progress_for_dl( 197 | aria_instance, err_message, sent_message_to_update_tg_p, None 198 | ) 199 | else: 200 | return False, "can't get metadata \n\n#MetaDataError" 201 | await asyncio.sleep(1) 202 | try: 203 | file = aria_instance.get_download(err_message) 204 | except aria2p.client.ClientException as ee: 205 | LOGGER.error(ee) 206 | return True, None 207 | to_upload_file = file.name 208 | com_g = file.is_complete 209 | else: 210 | await sent_message_to_update_tg_p.delete() 211 | to_upload_file, sent_message_to_update_tg_p = await download_tg(client=client, message=user_message) 212 | if not to_upload_file: 213 | return True, None 214 | com_g = True 215 | if is_zip: 216 | check_if_file = await create_archive(to_upload_file) 217 | if check_if_file is not None: 218 | to_upload_file = check_if_file 219 | # 220 | if is_unzip: 221 | try: 222 | check_ifi_file = get_base_name(to_upload_file) 223 | await unzip_me(to_upload_file) 224 | if os.path.exists(check_ifi_file): 225 | to_upload_file = check_ifi_file 226 | except Exception as ge: 227 | LOGGER.info(ge) 228 | LOGGER.info( 229 | f"Can't extract {os.path.basename(to_upload_file)}, Uploading the same file" 230 | ) 231 | 232 | if to_upload_file: 233 | if CUSTOM_FILE_NAME: 234 | if os.path.isfile(to_upload_file): 235 | os.rename(to_upload_file, 236 | f"{CUSTOM_FILE_NAME}{to_upload_file}") 237 | to_upload_file = f"{CUSTOM_FILE_NAME}{to_upload_file}" 238 | else: 239 | for root, _, files in os.walk(to_upload_file): 240 | LOGGER.info(files) 241 | for org in files: 242 | p_name = f"{root}/{org}" 243 | n_name = f"{root}/{CUSTOM_FILE_NAME}{org}" 244 | os.rename(p_name, n_name) 245 | to_upload_file = to_upload_file 246 | 247 | if cstom_file_name: 248 | os.rename(to_upload_file, cstom_file_name) 249 | to_upload_file = cstom_file_name 250 | # 251 | response = {} 252 | #LOGGER.info(response) 253 | user_id = user_message.from_user.id 254 | if com_g: 255 | if is_cloud: 256 | await upload_to_gdrive( 257 | to_upload_file, sent_message_to_update_tg_p, user_message, user_id 258 | ) 259 | else: 260 | final_response = await upload_to_tg( 261 | sent_message_to_update_tg_p, to_upload_file, user_id, response, client 262 | ) 263 | if not final_response: 264 | return True, None 265 | try: 266 | message_to_send = "" 267 | for key_f_res_se in final_response: 268 | local_file_name = key_f_res_se 269 | message_id = final_response[key_f_res_se] 270 | channel_id = str(sent_message_to_update_tg_p.chat.id)[4:] 271 | private_link = f"https://t.me/c/{channel_id}/{message_id}" 272 | message_to_send += "👉 " 275 | message_to_send += local_file_name 276 | message_to_send += "" 277 | message_to_send += "\n" 278 | if message_to_send != "": 279 | mention_req_user = ( 280 | f"Your Requested Files\n\n" 281 | ) 282 | message_to_send = mention_req_user + message_to_send 283 | message_to_send = message_to_send + "\n\n" + "#uploads" 284 | else: 285 | message_to_send = "FAILED to upload files. 😞😞" 286 | await user_message.reply_text( 287 | text=message_to_send, quote=True, disable_web_page_preview=True 288 | ) 289 | except Exception as go: 290 | LOGGER.error(go) 291 | return True, None 292 | 293 | 294 | # 295 | 296 | 297 | # https://github.com/jaskaranSM/UniBorg/blob/6d35cf452bce1204613929d4da7530058785b6b1/stdplugins/aria.py#L136-L164 298 | 299 | # todo- so much unwanted code, I will remove in future after some testing 300 | async def check_progress_for_dl(aria2, gid, event, previous_message): 301 | while True: 302 | try: 303 | file = aria2.get_download(gid) 304 | complete = file.is_complete 305 | is_file = file.seeder 306 | if not complete: 307 | if not file.error_message: 308 | if file.has_failed: 309 | LOGGER.info( 310 | f"Cancelling downloading of {file.name} may be due to slow torrent" 311 | ) 312 | await event.reply( 313 | f"Download cancelled :\n{file.name}\n\n #MetaDataError", quote=True 314 | ) 315 | file.remove(force=True, files=True) 316 | return 317 | else: 318 | msg = file.error_message 319 | LOGGER.info(msg) 320 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 321 | await event.reply(f"`{msg}`") 322 | return 323 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 324 | # await check_progress_for_dl(aria2, gid, event, previous_message) 325 | else: 326 | LOGGER.info( 327 | f"Downloaded Successfully: `{file.name} ({file.total_length_string()})` 🤒" 328 | ) 329 | # await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 330 | if not file.is_metadata: 331 | await event.edit( 332 | f"**Status:** `Downloaded ✅`\n\n**📝 FileName:** `{file.name}`\n\n**📎 Total Size:** `({file.total_length_string()})` \n\n#Downloaded" 333 | ) 334 | return 335 | except aria2p.client.ClientException: 336 | await event.reply( 337 | f"Download cancelled :\n{file.name} ({file.total_length_string()})", quote=True 338 | ) 339 | return 340 | except MessageNotModified as ep: 341 | LOGGER.info(ep) 342 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 343 | # await check_progress_for_dl(aria2, gid, event, previous_message) 344 | return 345 | except FloodWait as e: 346 | LOGGER.info(e) 347 | time.sleep(e.x) 348 | except Exception as e: 349 | LOGGER.info(str(e)) 350 | if "not found" in str(e) or "'file'" in str(e): 351 | await event.edit( 352 | f"Download cancelled :\n{file.name} ({file.total_length_string()})" 353 | ) 354 | return 355 | else: 356 | LOGGER.info(str(e)) 357 | await event.edit( 358 | "error :\n{} \n\n#error".format(str(e)) 359 | ) 360 | return 361 | 362 | 363 | # https://github.com/jaskaranSM/UniBorg/blob/6d35cf452bce1204613929d4da7530058785b6b1/stdplugins/aria.py#L136-L164 364 | 365 | 366 | async def check_metadata(aria2, gid): 367 | file = aria2.get_download(gid) 368 | 369 | if not file.followed_by_ids: 370 | # https://t.me/c/1213160642/496 371 | return None 372 | new_gid = file.followed_by_ids[0] 373 | LOGGER.info("Changing GID " + gid + " to " + new_gid) 374 | return new_gid 375 | -------------------------------------------------------------------------------- /tobrot/helper_funcs/upload_to_tg.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # (c) Shrimadhav U K | gautamajay52 4 | 5 | import asyncio 6 | import logging 7 | import os 8 | import re 9 | import shutil 10 | import subprocess 11 | import time 12 | from functools import partial 13 | from pathlib import Path 14 | 15 | import pyrogram.types as pyrogram 16 | import requests 17 | from hachoir.metadata import extractMetadata 18 | from hachoir.parser import createParser 19 | from hurry.filesize import size 20 | from PIL import Image 21 | from pyrogram.errors import FloodWait, MessageNotModified 22 | from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message 23 | from pyrogram.types import InputMediaAudio, InputMediaDocument, InputMediaVideo 24 | from requests.utils import requote_uri 25 | from tobrot import ( 26 | DESTINATION_FOLDER, 27 | DOWNLOAD_LOCATION, 28 | EDIT_SLEEP_TIME_OUT, 29 | INDEX_LINK, 30 | LOGGER, 31 | RCLONE_CONFIG, 32 | TG_MAX_FILE_SIZE, 33 | UPLOAD_AS_DOC, 34 | gDict, 35 | user_specific_config, 36 | ) 37 | from tobrot.helper_funcs.copy_similar_file import copy_file 38 | from tobrot.helper_funcs.display_progress import humanbytes, Progress 39 | from tobrot.helper_funcs.help_Nekmo_ffmpeg import take_screen_shot 40 | from tobrot.helper_funcs.split_large_files import split_large_files 41 | 42 | # stackoverflow🤐 43 | def getFolderSize(p): 44 | prepend = partial(os.path.join, p) 45 | return sum( 46 | [ 47 | (os.path.getsize(f) if os.path.isfile(f) else getFolderSize(f)) 48 | for f in map(prepend, os.listdir(p)) 49 | ] 50 | ) 51 | 52 | 53 | async def upload_to_tg( 54 | message, 55 | local_file_name, 56 | from_user, 57 | dict_contatining_uploaded_files, 58 | client, 59 | edit_media=False, 60 | yt_thumb=None, 61 | ): 62 | base_file_name = os.path.basename(local_file_name) 63 | caption_str = "" 64 | caption_str += "" 65 | caption_str += base_file_name 66 | caption_str += "" 67 | if os.path.isdir(local_file_name): 68 | directory_contents = os.listdir(local_file_name) 69 | directory_contents.sort() 70 | # number_of_files = len(directory_contents) 71 | LOGGER.info(directory_contents) 72 | new_m_esg = message 73 | if not message.photo: 74 | new_m_esg = await message.reply_text( 75 | f"Found {len(directory_contents)} Files 📡", 76 | quote=True 77 | # reply_to_message_id=message.message_id 78 | ) 79 | for single_file in directory_contents: 80 | # recursion: will this FAIL somewhere? 81 | await upload_to_tg( 82 | new_m_esg, 83 | os.path.join(local_file_name, single_file), 84 | from_user, 85 | dict_contatining_uploaded_files, 86 | client, 87 | edit_media, 88 | yt_thumb, 89 | ) 90 | else: 91 | if os.path.getsize(local_file_name) > TG_MAX_FILE_SIZE: 92 | LOGGER.info("TODO") 93 | d_f_s = humanbytes(os.path.getsize(local_file_name)) 94 | i_m_s_g = await message.reply_text( 95 | "Telegram does not support uploading this file.\n" 96 | f"Detected File Size: {d_f_s} 😡\n" 97 | "\n🤖 trying to split the files 🌝🌝🌚" 98 | ) 99 | splitted_dir = await split_large_files(local_file_name) 100 | totlaa_sleif = os.listdir(splitted_dir) 101 | totlaa_sleif.sort() 102 | number_of_files = len(totlaa_sleif) 103 | LOGGER.info(totlaa_sleif) 104 | ba_se_file_name = os.path.basename(local_file_name) 105 | await i_m_s_g.edit_text( 106 | f"Detected File Size: {d_f_s} 😡\n" 107 | f"{ba_se_file_name} splitted into {number_of_files} files.\n" 108 | "Trying to upload to Telegram, now ..." 109 | ) 110 | for le_file in totlaa_sleif: 111 | # recursion: will this FAIL somewhere? 112 | await upload_to_tg( 113 | message, 114 | os.path.join(splitted_dir, le_file), 115 | from_user, 116 | dict_contatining_uploaded_files, 117 | client, 118 | edit_media, 119 | yt_thumb, 120 | ) 121 | else: 122 | sizze = os.path.getsize(local_file_name) 123 | sent_message = await upload_single_file( 124 | message, 125 | local_file_name, 126 | caption_str, 127 | from_user, 128 | client, 129 | edit_media, 130 | yt_thumb, 131 | ) 132 | if sent_message is not None: 133 | dict_contatining_uploaded_files[ 134 | os.path.basename(local_file_name) 135 | ] = sent_message.message_id 136 | else: 137 | return 138 | # await message.delete() 139 | return dict_contatining_uploaded_files 140 | 141 | 142 | # © gautamajay52 thanks to Rclone team for this wonderful tool.🧘 143 | 144 | 145 | async def upload_to_gdrive(file_upload, message, messa_ge, g_id): 146 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 147 | del_it = await message.edit_text( 148 | f"🔊 Now Uploading to ☁️ Cloud!!!" 149 | ) 150 | if not os.path.exists("rclone.conf"): 151 | with open("rclone.conf", "w+", newline="\n", encoding="utf-8") as fole: 152 | fole.write(f"{RCLONE_CONFIG}") 153 | if os.path.exists("rclone.conf"): 154 | with open("rclone.conf", "r+") as file: 155 | con = file.read() 156 | gUP = re.findall("\[(.*)\]", con)[0] 157 | LOGGER.info(gUP) 158 | destination = f"{DESTINATION_FOLDER}" 159 | file_upload = str(Path(file_upload).resolve()) 160 | LOGGER.info(file_upload) 161 | if os.path.isfile(file_upload): 162 | g_au = [ 163 | "rclone", 164 | "copy", 165 | "--config=rclone.conf", 166 | f"{file_upload}", 167 | f"{gUP}:{destination}", 168 | "-v", 169 | ] 170 | LOGGER.info(g_au) 171 | tmp = await asyncio.create_subprocess_exec( 172 | *g_au, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 173 | ) 174 | pro, cess = await tmp.communicate() 175 | LOGGER.info(pro.decode("utf-8")) 176 | LOGGER.info(cess.decode("utf-8")) 177 | gk_file = re.escape(os.path.basename(file_upload)) 178 | LOGGER.info(gk_file) 179 | with open("filter.txt", "w+", encoding="utf-8") as filter: 180 | print(f"+ {gk_file}\n- *", file=filter) 181 | 182 | t_a_m = [ 183 | "rclone", 184 | "lsf", 185 | "--config=rclone.conf", 186 | "-F", 187 | "i", 188 | "--filter-from=filter.txt", 189 | "--files-only", 190 | f"{gUP}:{destination}", 191 | ] 192 | gau_tam = await asyncio.create_subprocess_exec( 193 | *t_a_m, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 194 | ) 195 | # os.remove("filter.txt") 196 | gau, tam = await gau_tam.communicate() 197 | gautam = gau.decode().strip() 198 | LOGGER.info(gau.decode()) 199 | LOGGER.info(tam.decode()) 200 | # os.remove("filter.txt") 201 | gauti = f"https://drive.google.com/file/d/{gautam}/view?usp=drivesdk" 202 | gjay = size(os.path.getsize(file_upload)) 203 | button = [] 204 | button.append( 205 | [pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️", url=f"{gauti}")] 206 | ) 207 | if INDEX_LINK: 208 | indexurl = f"{INDEX_LINK}/{os.path.basename(file_upload)}" 209 | tam_link = requests.utils.requote_uri(indexurl) 210 | LOGGER.info(tam_link) 211 | button.append( 212 | [ 213 | pyrogram.InlineKeyboardButton( 214 | text="ℹ️ IndexUrl ℹ️", url=f"{tam_link}" 215 | ) 216 | ] 217 | ) 218 | button_markup = pyrogram.InlineKeyboardMarkup(button) 219 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 220 | await messa_ge.reply_text( 221 | f"🤖: Uploaded successfully `{os.path.basename(file_upload)}` 🤒\n📀 Size: {gjay}", 222 | reply_markup=button_markup, 223 | ) 224 | os.remove(file_upload) 225 | await del_it.delete() 226 | else: 227 | tt = os.path.join(destination, os.path.basename(file_upload)) 228 | LOGGER.info(tt) 229 | t_am = [ 230 | "rclone", 231 | "copy", 232 | "--config=rclone.conf", 233 | f"{file_upload}", 234 | f"{gUP}:{tt}", 235 | "-v", 236 | ] 237 | LOGGER.info(t_am) 238 | tmp = await asyncio.create_subprocess_exec( 239 | *t_am, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 240 | ) 241 | pro, cess = await tmp.communicate() 242 | LOGGER.info(pro.decode("utf-8")) 243 | LOGGER.info(cess.decode("utf-8")) 244 | g_file = re.escape(os.path.basename(file_upload)) 245 | LOGGER.info(g_file) 246 | with open("filter1.txt", "w+", encoding="utf-8") as filter1: 247 | print(f"+ {g_file}/\n- *", file=filter1) 248 | 249 | g_a_u = [ 250 | "rclone", 251 | "lsf", 252 | "--config=rclone.conf", 253 | "-F", 254 | "i", 255 | "--filter-from=filter1.txt", 256 | "--dirs-only", 257 | f"{gUP}:{destination}", 258 | ] 259 | gau_tam = await asyncio.create_subprocess_exec( 260 | *g_a_u, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE 261 | ) 262 | # os.remove("filter1.txt") 263 | gau, tam = await gau_tam.communicate() 264 | gautam = gau.decode("utf-8") 265 | LOGGER.info(gautam) 266 | LOGGER.info(tam.decode("utf-8")) 267 | # os.remove("filter1.txt") 268 | gautii = f"https://drive.google.com/folderview?id={gautam}" 269 | gjay = size(getFolderSize(file_upload)) 270 | LOGGER.info(gjay) 271 | button = [] 272 | button.append( 273 | [pyrogram.InlineKeyboardButton(text="☁️ CloudUrl ☁️", url=f"{gautii}")] 274 | ) 275 | if INDEX_LINK: 276 | indexurl = f"{INDEX_LINK}/{os.path.basename(file_upload)}/" 277 | tam_link = requests.utils.requote_uri(indexurl) 278 | LOGGER.info(tam_link) 279 | button.append( 280 | [ 281 | pyrogram.InlineKeyboardButton( 282 | text="ℹ️ IndexUrl ℹ️", url=f"{tam_link}" 283 | ) 284 | ] 285 | ) 286 | button_markup = pyrogram.InlineKeyboardMarkup(button) 287 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 288 | await messa_ge.reply_text( 289 | f"🤖: Uploaded successfully `{os.path.basename(file_upload)}` 🤒\n📀 Size: {gjay}", 290 | reply_markup=button_markup, 291 | ) 292 | shutil.rmtree(file_upload) 293 | await del_it.delete() 294 | 295 | 296 | 297 | 298 | 299 | async def upload_single_file( 300 | message, local_file_name, caption_str, from_user, client, edit_media, yt_thumb 301 | ): 302 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 303 | local_file_name = str(Path(local_file_name).resolve()) 304 | sent_message = None 305 | start_time = time.time() 306 | # 307 | thumbnail_location = os.path.join( 308 | DOWNLOAD_LOCATION, "thumbnails", str(from_user) + ".jpg" 309 | ) 310 | # LOGGER.info(thumbnail_location) 311 | dyna_user_config_upload_as_doc = False 312 | for key in iter(user_specific_config): 313 | if key == from_user: 314 | dyna_user_config_upload_as_doc=user_specific_config[key].upload_as_doc 315 | LOGGER.info(f'Found dyanamic config for user {from_user}') 316 | # 317 | if UPLOAD_AS_DOC.upper() == "TRUE" or dyna_user_config_upload_as_doc: 318 | # todo 319 | thumb = None 320 | thumb_image_path = None 321 | if os.path.exists(thumbnail_location): 322 | thumb_image_path = await copy_file( 323 | thumbnail_location, os.path.dirname(os.path.abspath(local_file_name)) 324 | ) 325 | thumb = thumb_image_path 326 | message_for_progress_display = message 327 | if not edit_media: 328 | message_for_progress_display = await message.reply_text( 329 | "**Status :** `Starting Uploading 📤`\n\n**• FileName :** `{}`".format(os.path.basename(local_file_name)) 330 | ) 331 | prog = Progress(from_user, client, message_for_progress_display) 332 | sent_message = await message.reply_document( 333 | document=local_file_name, 334 | thumb=thumb, 335 | caption=caption_str, 336 | parse_mode="html", 337 | disable_notification=True, 338 | progress=prog.progress_for_pyrogram, 339 | progress_args=( 340 | f"**• Uploading :** `{os.path.basename(local_file_name)}`", 341 | start_time, 342 | ), 343 | ) 344 | if message.message_id != message_for_progress_display.message_id: 345 | try: 346 | await message_for_progress_display.delete() 347 | except FloodWait as gf: 348 | time.sleep(gf.x) 349 | except Exception as rr: 350 | LOGGER.warning(str(rr)) 351 | os.remove(local_file_name) 352 | if thumb is not None: 353 | os.remove(thumb) 354 | else: 355 | try: 356 | message_for_progress_display = message 357 | if not edit_media: 358 | message_for_progress_display = await message.reply_text( 359 | "**Status :** `Starting Uploading 📤`\n\n**• FileName :** `{}`".format(os.path.basename(local_file_name)) 360 | ) 361 | prog = Progress(from_user, client, message_for_progress_display) 362 | if local_file_name.upper().endswith(("MKV", "MP4", "WEBM", "FLV", "3GP", "AVI", "MOV", "OGG", "WMV", "M4V", "TS", "MPG", "MTS", "M2TS")): 363 | duration = 0 364 | try: 365 | metadata = extractMetadata(createParser(local_file_name)) 366 | if metadata.has("duration"): 367 | duration = metadata.get("duration").seconds 368 | except Exception as g_e: 369 | LOGGER.info(g_e) 370 | width = 0 371 | height = 0 372 | thumb_image_path = None 373 | if os.path.exists(thumbnail_location): 374 | thumb_image_path = await copy_file( 375 | thumbnail_location, 376 | os.path.dirname(os.path.abspath(local_file_name)), 377 | ) 378 | else: 379 | if not yt_thumb: 380 | LOGGER.info("Taking Screenshot..") 381 | thumb_image_path = await take_screen_shot( 382 | local_file_name, 383 | os.path.dirname(os.path.abspath(local_file_name)), 384 | (duration / 2), 385 | ) 386 | else: 387 | req = requests.get(yt_thumb) 388 | thumb_image_path = os.path.join( 389 | os.path.dirname(os.path.abspath(local_file_name)), 390 | str(time.time()) + ".jpg", 391 | ) 392 | with open(thumb_image_path, "wb") as thum: 393 | thum.write(req.content) 394 | img = Image.open(thumb_image_path).convert("RGB") 395 | img.save(thumb_image_path, format="jpeg") 396 | # get the correct width, height, and duration for videos greater than 10MB 397 | if os.path.exists(thumb_image_path): 398 | metadata = extractMetadata(createParser(thumb_image_path)) 399 | if metadata.has("width"): 400 | width = metadata.get("width") 401 | if metadata.has("height"): 402 | height = metadata.get("height") 403 | # ref: https://t.me/PyrogramChat/44663 404 | # https://stackoverflow.com/a/21669827/4723940 405 | Image.open(thumb_image_path).convert("RGB").save( 406 | thumb_image_path 407 | ) 408 | img = Image.open(thumb_image_path) 409 | # https://stackoverflow.com/a/37631799/4723940 410 | img.resize((320, height)) 411 | img.save(thumb_image_path, "JPEG") 412 | # https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#create-thumbnails 413 | # 414 | thumb = None 415 | if thumb_image_path is not None and os.path.isfile(thumb_image_path): 416 | thumb = thumb_image_path 417 | # send video 418 | if edit_media and message.photo: 419 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 420 | sent_message = await message.edit_media( 421 | media=InputMediaVideo( 422 | media=local_file_name, 423 | thumb=thumb, 424 | caption=caption_str, 425 | parse_mode="html", 426 | width=width, 427 | height=height, 428 | duration=duration, 429 | supports_streaming=True, 430 | ) 431 | # quote=True, 432 | ) 433 | else: 434 | sent_message = await message.reply_video( 435 | video=local_file_name, 436 | caption=caption_str, 437 | parse_mode="html", 438 | duration=duration, 439 | width=width, 440 | height=height, 441 | thumb=thumb, 442 | supports_streaming=True, 443 | disable_notification=True, 444 | progress=prog.progress_for_pyrogram, 445 | progress_args=( 446 | f"**• Uploading :** `{os.path.basename(local_file_name)}`", 447 | start_time, 448 | ), 449 | ) 450 | if thumb is not None: 451 | os.remove(thumb) 452 | elif local_file_name.upper().endswith(("MP3", "M4A", "M4B", "FLAC", "WAV")): 453 | metadata = extractMetadata(createParser(local_file_name)) 454 | duration = 0 455 | title = "" 456 | artist = "" 457 | if metadata.has("duration"): 458 | duration = metadata.get("duration").seconds 459 | if metadata.has("title"): 460 | title = metadata.get("title") 461 | if metadata.has("artist"): 462 | artist = metadata.get("artist") 463 | thumb_image_path = None 464 | if os.path.isfile(thumbnail_location): 465 | thumb_image_path = await copy_file( 466 | thumbnail_location, 467 | os.path.dirname(os.path.abspath(local_file_name)), 468 | ) 469 | thumb = None 470 | if thumb_image_path is not None and os.path.isfile(thumb_image_path): 471 | thumb = thumb_image_path 472 | # send audio 473 | if edit_media and message.photo: 474 | await asyncio.sleep(EDIT_SLEEP_TIME_OUT) 475 | sent_message = await message.edit_media( 476 | media=InputMediaAudio( 477 | media=local_file_name, 478 | thumb=thumb, 479 | caption=caption_str, 480 | parse_mode="html", 481 | duration=duration, 482 | performer=artist, 483 | title=title, 484 | ) 485 | ) 486 | else: 487 | sent_message = await message.reply_audio( 488 | audio=local_file_name, 489 | caption=caption_str, 490 | parse_mode="html", 491 | duration=duration, 492 | performer=artist, 493 | title=title, 494 | thumb=thumb, 495 | disable_notification=True, 496 | progress=prog.progress_for_pyrogram, 497 | progress_args=( 498 | f"**• Uploading :** `{os.path.basename(local_file_name)}`", 499 | start_time, 500 | ), 501 | ) 502 | if thumb is not None: 503 | os.remove(thumb) 504 | else: 505 | thumb_image_path = None 506 | if os.path.isfile(thumbnail_location): 507 | thumb_image_path = await copy_file( 508 | thumbnail_location, 509 | os.path.dirname(os.path.abspath(local_file_name)), 510 | ) 511 | # if a file, don't upload "thumb" 512 | # this "diff" is a major derp -_- 😔😭😭 513 | thumb = None 514 | if thumb_image_path is not None and os.path.isfile(thumb_image_path): 515 | thumb = thumb_image_path 516 | # 517 | # send document 518 | if edit_media and message.photo: 519 | sent_message = await message.edit_media( 520 | media=InputMediaDocument( 521 | media=local_file_name, 522 | thumb=thumb, 523 | caption=caption_str, 524 | parse_mode="html", 525 | ) 526 | ) 527 | else: 528 | sent_message = await message.reply_document( 529 | document=local_file_name, 530 | thumb=thumb, 531 | caption=caption_str, 532 | parse_mode="html", 533 | disable_notification=True, 534 | progress=prog.progress_for_pyrogram, 535 | progress_args=( 536 | f"**• Uploading :** `{os.path.basename(local_file_name)}`", 537 | start_time, 538 | ), 539 | ) 540 | if thumb is not None: 541 | os.remove(thumb) 542 | 543 | except MessageNotModified as oY: 544 | LOGGER.info(oY) 545 | except FloodWait as g: 546 | LOGGER.info(g) 547 | time.sleep(g.x) 548 | except Exception as e: 549 | LOGGER.info(e) 550 | await message_for_progress_display.edit_text("**FAILED**\n" + str(e)) 551 | else: 552 | if message.message_id != message_for_progress_display.message_id: 553 | try: 554 | if sent_message is not None: 555 | await message_for_progress_display.delete() 556 | except FloodWait as gf: 557 | time.sleep(gf.x) 558 | except Exception as rr: 559 | LOGGER.warning(str(rr)) 560 | await asyncio.sleep(5) 561 | os.remove(local_file_name) 562 | return sent_message 563 | -------------------------------------------------------------------------------- /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 | . --------------------------------------------------------------------------------