* Add betterer formattation and ffmpeg installation testing

* Update readme

* Better formattation

* Update readme with tg

* Change tg folder

* Add RRC

* Rename ...
This commit is contained in:
Dark1291 2025-02-05 13:20:20 +01:00 committed by GitHub
parent d7d137ed4e
commit c622cbbdf0
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
46 changed files with 1203 additions and 1841 deletions

108
README.md
View File

@ -9,23 +9,23 @@
<a href="https://www.paypal.com/donate/?hosted_button_id=UXTWMT8P6HE2C"> <a href="https://www.paypal.com/donate/?hosted_button_id=UXTWMT8P6HE2C">
<img src="https://img.shields.io/badge/_-Donate-red.svg?logo=githubsponsors&labelColor=555555&style=for-the-badge" alt="Donate"/> <img src="https://img.shields.io/badge/_-Donate-red.svg?logo=githubsponsors&labelColor=555555&style=for-the-badge" alt="Donate"/>
</a> </a>
<a href="https://github.com/Lovi-0/StreamingCommunity/commits"> <a href="https://github.com/Abc-dc/StreamingCommunity/commits">
<img src="https://img.shields.io/github/commit-activity/m/Lovi-0/StreamingCommunity?label=commits&style=for-the-badge" alt="Commits"/> <img src="https://img.shields.io/github/commit-activity/m/Abc-dc/StreamingCommunity?label=commits&style=for-the-badge" alt="Commits"/>
</a> </a>
<a href="https://github.com/Lovi-0/StreamingCommunity/commits"> <a href="https://github.com/Abc-dc/StreamingCommunity/commits">
<img src="https://img.shields.io/github/last-commit/Lovi-0/StreamingCommunity/main?label=&style=for-the-badge&display_timestamp=committer" alt="Last Commit"/> <img src="https://img.shields.io/github/last-commit/Abc-dc/StreamingCommunity/main?label=&style=for-the-badge&display_timestamp=committer" alt="Last Commit"/>
</a> </a>
</p> </p>
<p align="center"> <p align="center">
<a href="https://github.com/Lovi-0/StreamingCommunity/blob/main/LICENSE"> <a href="https://github.com/Abc-dc/StreamingCommunity/blob/main/LICENSE">
<img src="https://img.shields.io/badge/License-GPL_3.0-blue.svg?style=for-the-badge" alt="License"/> <img src="https://img.shields.io/badge/License-GPL_3.0-blue.svg?style=for-the-badge" alt="License"/>
</a> </a>
<a href="https://pypi.org/project/streamingcommunity"> <a href="https://pypi.org/project/streamingcommunity">
<img src="https://img.shields.io/pypi/dm/streamingcommunity?style=for-the-badge" alt="PyPI Downloads"/> <img src="https://img.shields.io/pypi/dm/streamingcommunity?style=for-the-badge" alt="PyPI Downloads"/>
</a> </a>
<a href="https://github.com/Lovi-0/StreamingCommunity"> <a href="https://github.com/Abc-dc/StreamingCommunity">
<img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Lovi-0/StreamingCommunity/main/Test/Util/loc-badge.json&style=for-the-badge" alt="Lines of Code"/> <img src="https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/Abc-dc/StreamingCommunity/main/Test/Util/loc-badge.json&style=for-the-badge" alt="Lines of Code"/>
</a> </a>
</p> </p>
@ -44,7 +44,10 @@
- 📩 [Request](#requests-settings) - 📩 [Request](#requests-settings)
- 📥 [Download](#m3u8_download-settings) - 📥 [Download](#m3u8_download-settings)
- 🔍 [Parser](#m3u8_parser-settings) - 🔍 [Parser](#m3u8_parser-settings)
- 📝 [Command](#command)
- 💻 [Examples of terminal](#examples-of-terminal-usage)
- 🐳 [Docker](#docker) - 🐳 [Docker](#docker)
- 📝 [Telegram Usage](#telegram-usage)
- 🎓 [Tutorial](#tutorials) - 🎓 [Tutorial](#tutorials)
- 📝 [To do](#to-do) - 📝 [To do](#to-do)
- 💬 [Support](#support) - 💬 [Support](#support)
@ -55,16 +58,13 @@
# Installation # Installation
<p align="center"> <p align="center">
<a href="https://github.com/Lovi-0/StreamingCommunity/releases/latest/download/StreamingCommunity.exe"> <a href="https://github.com/Abc-dc/StreamingCommunity/releases/latest/download/StreamingCommunity.exe">
<img src="https://img.shields.io/badge/-Windows_x64-blue.svg?style=for-the-badge&logo=windows" alt="Windows"> <img src="https://img.shields.io/badge/-Windows_x64-blue.svg?style=for-the-badge&logo=windows" alt="Windows">
</a> </a>
<a href="https://pypi.org/project/StreamingCommunity"> <a href="https://github.com/Abc-dc/StreamingCommunity/releases/latest/download/StreamingCommunity.zip">
<img src="https://img.shields.io/badge/-PyPI-blue.svg?logo=pypi&labelColor=555555&style=for-the-badge" alt="PyPI">
</a>
<a href="https://github.com/Lovi-0/StreamingCommunity/releases/latest/download/StreamingCommunity.zip">
<img src="https://img.shields.io/badge/-Source_tar-green.svg?style=for-the-badge" alt="Source Tarball"> <img src="https://img.shields.io/badge/-Source_tar-green.svg?style=for-the-badge" alt="Source Tarball">
</a> </a>
<a href="https://github.com/Lovi-0/StreamingCommunity/releases"> <a href="https://github.com/Abc-dc/StreamingCommunity/releases">
<img src="https://img.shields.io/badge/-All_Versions-lightgrey.svg?style=for-the-badge" alt="All Versions"> <img src="https://img.shields.io/badge/-All_Versions-lightgrey.svg?style=for-the-badge" alt="All Versions">
</a> </a>
</p> </p>
@ -286,25 +286,37 @@ The configuration file is divided into several main sections:
`<br/><br/>` `<br/><br/>`
- `movie_folder_name`: The name of the subdirectory where movies will be stored. - `movie_folder_name`: The name of the subdirectory where movies will be stored.
* Can be changed from terminal with `--movie_folder_name`
<br/><br/>
- `serie_folder_name`: The name of the subdirectory where TV series will be stored. - `serie_folder_name`: The name of the subdirectory where TV series will be stored.
* Can be changed from terminal with `--serie_folder_name`
<br/><br/>
- `map_episode_name`: Template for TV series episode filenames - `map_episode_name`: Template for TV series episode filenames
### Episode name usage: ### Episode name usage:
You can choose different vars: You can choose different vars:
* `%(tv_name)` : Is the name of TV Show * `%(tv_name)` : Is the name of TV Show
* `%(season)` : Is the number of the season * `%(season)` : Is the number of the season
* `%(episode)` : Is the number of the episode * `%(episode)` : Is the number of the episode
* `%(episode_name)` : Is the name of the episode * `%(episode_name)` : Is the name of the episode
`<br/><br/>` `<br/><br/>`
* Can be changed from terminal with `--map_episode_name`
<br/><br/>
- `add_siteName`: If set to true, appends the site_name to the root path before the movie and serie folders. - `add_siteName`: If set to true, appends the site_name to the root path before the movie and serie folders.
- `disable_searchDomain`: If set to true, disables the search for a new domain for all sites. * Can be changed from terminal with `--add_siteName true/false`
- `not_close`: If set to true, keeps the program running after the download is complete. <br/><br/>
- `disable_searchDomain`: If set to true, disables the search for a new domain for all sites.
* Can be changed from terminal with `--disable_searchDomain true/false`
<br/><br/>
- `not_close`: If set to true, keeps the program running after the download is complete.
* Can be changed from terminal with `--not_close true/false`
<br/><br/>
### qBittorrent Configuration ### qBittorrent Configuration
@ -350,7 +362,13 @@ The configuration file is divided into several main sections:
- `tqdm_delay`: Delay between progress bar updates - `tqdm_delay`: Delay between progress bar updates
- `tqdm_use_large_bar`: Use detailed progress bar (recommended for desktop) set to false for mobile - `tqdm_use_large_bar`: Use detailed progress bar (recommended for desktop) set to false for mobile
- `default_video_workser`: Number of threads for video download - `default_video_workser`: Number of threads for video download
* Can be changed from terminal with `--default_video_worker <number>`
<br/><br/>
- `default_audio_workser`: Number of threads for audio download - `default_audio_workser`: Number of threads for audio download
* Can be changed from terminal with `--default_audio_worker <number>`
<br/><br/>
- `cleanup_tmp_folder`: Remove temporary .ts files after download - `cleanup_tmp_folder`: Remove temporary .ts files after download
> [!IMPORTANT] > [!IMPORTANT]
@ -361,6 +379,9 @@ The configuration file is divided into several main sections:
### Language Settings ### Language Settings
The following codes can be used for `specific_list_audio` and `specific_list_subtitles`: The following codes can be used for `specific_list_audio` and `specific_list_subtitles`:
* Can be changed from terminal with `--specific_list_audio ita,eng` for audio
* Can be changed from terminal with `--specific_list_subtitles eng,spa` for subtitles
``` ```
ara - Arabic eng - English ita - Italian por - Portuguese ara - Arabic eng - English ita - Italian por - Portuguese
@ -432,6 +453,21 @@ You can download VLC Media Player from the [official website](https://www.videol
- Enter a season number followed by `-*` to download from that season to the end. - Enter a season number followed by `-*` to download from that season to the end.
* **Example:** `3-*` will download from *Season 3* to the final season. * **Example:** `3-*` will download from *Season 3* to the final season.
# Examples of terminal usage
```bash
# Change video and audio workers
python test_run.py --default_video_worker 8 --default_audio_worker 8
# Set specific languages
python test_run.py --specific_list_audio ita,eng --specific_list_subtitles eng,spa
# Keep console open after download
python test_run.py --not_close true
# Disable domain search and add site name
python test_run.py --disable_searchDomain true --add_siteName true
```
# Docker # Docker
@ -466,15 +502,43 @@ make LOCAL_DIR=/path/to/download run-container
The `run-container` command mounts also the `config.json` file, so any change to the configuration file is reflected immediately without having to rebuild the image. The `run-container` command mounts also the `config.json` file, so any change to the configuration file is reflected immediately without having to rebuild the image.
# Telegram Usage
## Configuration
You need to create an .env file and enter your Telegram token
and user ID to authorize only one user to use it
## .env Example:
```
TOKEN_TELEGRAM=IlTuo2131TOKEN$12D3Telegram
AUTHORIZED_USER_ID=12345678
DEBUG=False
```
## Install Python Dependencies
```bash
pip install -r requirements.txt
```
## On Linux/MacOS:
```bash
python3 telegram_bot.py
```
# Website Status # Website Status
| Website | Status | | Website | Status |
|:-------------------|:------:| |:-------------------|:------:|
| [1337xx](https://1337xx.to/) | ✅ | | [1337xx](https://1337xx.to/) | ✅ |
| [AltadefinizioneGratis](https://altadefinizionegratis.site/) | ✅ | | [AltadefinizioneGratis](https://altadefinizionegratis.pro/) | ✅ |
| [AnimeUnity](https://animeunity.so/) | ✅ | | [AnimeUnity](https://animeunity.so/) | ✅ |
| [Ilcorsaronero](https://ilcorsaronero.link/) | ✅ | | [Ilcorsaronero](https://ilcorsaronero.link/) | ✅ |
| [CB01New](https://cb01new.video/) | ✅ | | [CB01New](https://cb01new.media/) | ✅ |
| [DDLStreamItaly](https://ddlstreamitaly.co/) | ✅ | | [DDLStreamItaly](https://ddlstreamitaly.co/) | ✅ |
| [GuardaSerie](https://guardaserie.meme/) | ✅ | | [GuardaSerie](https://guardaserie.meme/) | ✅ |
| [MostraGuarda](https://mostraguarda.stream/) | ✅ | | [MostraGuarda](https://mostraguarda.stream/) | ✅ |
@ -490,7 +554,7 @@ The `run-container` command mounts also the `config.json` file, so any change to
# To Do # To Do
- Finish [website API](https://github.com/Lovi-0/StreamingCommunity/tree/test_gui_1) - Finish [website API](https://github.com/Abc-dc/StreamingCommunity/tree/test_gui_1)
# Contributing # Contributing
@ -508,6 +572,6 @@ This software is provided "as is", without warranty of any kind, express or impl
## Contributors ## Contributors
<a href="https://github.com/Lovi-0/StreamingCommunity/graphs/contributors" alt="View Contributors"> <a href="https://github.com/Abc-dc/StreamingCommunity/graphs/contributors" alt="View Contributors">
<img src="https://contrib.rocks/image?repo=Lovi-0/StreamingCommunity&max=1000&columns=10" alt="Contributors" /> <img src="https://contrib.rocks/image?repo=Abc-dc/StreamingCommunity&max=1000&columns=10" alt="Contributors" />
</a> </a>

View File

@ -1,5 +1,7 @@
# 02.07.24 # 02.07.24
import sys
import subprocess
from urllib.parse import quote_plus from urllib.parse import quote_plus
@ -11,12 +13,6 @@ from StreamingCommunity.Util.console import console, msg
from .site import title_search, run_get_select_title, media_search_manager from .site import title_search, run_get_select_title, media_search_manager
from .title import download_title from .title import download_title
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
import sys
import subprocess
# Variable # Variable
indice = 8 indice = 8
@ -31,25 +27,9 @@ def search(string_to_search: str = None, get_onylDatabase: bool = False):
""" """
Main function of the application for film and series. Main function of the application for film and series.
""" """
if TELEGRAM_BOT: if string_to_search is None:
bot = get_bot_instance()
# Chiedi la scelta all'utente con il bot Telegram
string_to_search = bot.ask(
"key_search",
f"Inserisci la parola da cercare\noppure 🔙 back per tornare alla scelta: ",
None
)
if string_to_search == 'back':
# Riavvia lo script
# Chiude il processo attuale e avvia una nuova istanza dello script
subprocess.Popen([sys.executable] + sys.argv)
sys.exit()
else:
if string_to_search is None:
string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip() string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip()
# Search on database # Search on database
len_database = title_search(quote_plus(string_to_search)) len_database = title_search(quote_plus(string_to_search))
@ -69,4 +49,4 @@ def search(string_to_search: str = None, get_onylDatabase: bool = False):
console.print(f"\n[red]Nothing matching was found for[white]: [purple]{string_to_search}") console.print(f"\n[red]Nothing matching was found for[white]: [purple]{string_to_search}")
# Retry # Retry
search() search()

View File

@ -17,10 +17,6 @@ from StreamingCommunity.Api.Template import get_select_title
from StreamingCommunity.Api.Template.Util import search_domain from StreamingCommunity.Api.Template.Util import search_domain
from StreamingCommunity.Api.Template.Class.SearchType import MediaManager from StreamingCommunity.Api.Template.Class.SearchType import MediaManager
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
# Variable # Variable
from .costant import SITE_NAME, DOMAIN_NOW from .costant import SITE_NAME, DOMAIN_NOW
@ -40,10 +36,6 @@ def title_search(word_to_search: str) -> int:
Returns: Returns:
- int: The number of titles found. - int: The number of titles found.
""" """
if TELEGRAM_BOT:
bot = get_bot_instance()
media_search_manager.clear() media_search_manager.clear()
table_show_manager.clear() table_show_manager.clear()
@ -69,10 +61,6 @@ def title_search(word_to_search: str) -> int:
# Create soup and find table # Create soup and find table
soup = BeautifulSoup(response.text, "html.parser") soup = BeautifulSoup(response.text, "html.parser")
if TELEGRAM_BOT:
# Inizializza la lista delle scelte
choices = []
for tr in soup.find_all('tr'): for tr in soup.find_all('tr'):
try: try:
@ -85,22 +73,9 @@ def title_search(word_to_search: str) -> int:
'size': tr.find_all("td")[-2].get_text(strip=True) 'size': tr.find_all("td")[-2].get_text(strip=True)
} }
if TELEGRAM_BOT:
# Crea una stringa formattata per ogni scelta con numero
choice_text = f"{len(choices)} - {title_info.get('name')} ({title_info.get('type')}) - {title_info.get('date')}"
choices.append(choice_text)
media_search_manager.add_media(title_info)
except Exception as e: except Exception as e:
print(f"Error parsing a film entry: {e}") print(f"Error parsing a film entry: {e}")
if TELEGRAM_BOT:
# Se ci sono scelte, inviale a Telegram
if choices:
# Invio a telegram la lista
bot.send_message(f"Lista dei risultati:", choices)
# Return the number of titles found # Return the number of titles found
return media_search_manager.get_length() return media_search_manager.get_length()

View File

@ -23,11 +23,6 @@ from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
# Config # Config
from .costant import DOMAIN_NOW, SITE_NAME, MOVIE_FOLDER from .costant import DOMAIN_NOW, SITE_NAME, MOVIE_FOLDER
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.HelpTg.session import get_session, updateScriptId, deleteScriptId
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
def download_title(select_title: MediaItem): def download_title(select_title: MediaItem):
""" """
@ -36,13 +31,6 @@ def download_title(select_title: MediaItem):
Parameters: Parameters:
- select_title (MediaItem): The media item to be downloaded. This should be an instance of the MediaItem class, containing attributes like `name` and `url`. - select_title (MediaItem): The media item to be downloaded. This should be an instance of the MediaItem class, containing attributes like `name` and `url`.
""" """
if TELEGRAM_BOT:
bot = get_bot_instance()
bot.send_message(f"Download in corso:\n{select_title.name}", None)
script_id = get_session()
if script_id != "unknown":
updateScriptId(script_id, select_title.name)
start_message() start_message()
console.print(f"[yellow]Download: [red]{select_title.name} \n") console.print(f"[yellow]Download: [red]{select_title.name} \n")
print() print()
@ -72,10 +60,4 @@ def download_title(select_title: MediaItem):
manager = TOR_downloader() manager = TOR_downloader()
manager.add_magnet_link(final_url) manager.add_magnet_link(final_url)
manager.start_download() manager.start_download()
manager.move_downloaded_files(mp4_path) manager.move_downloaded_files(mp4_path)
if TELEGRAM_BOT:
# Delete script_id
script_id = get_session()
if script_id != "unknown":
deleteScriptId(script_id)

View File

@ -1,20 +1,19 @@
# 26.05.24 # 26.05.24
import sys
import subprocess
from urllib.parse import quote_plus from urllib.parse import quote_plus
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console, msg
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
# Logic class # Logic class
from .site import title_search, run_get_select_title, media_search_manager from .site import title_search, run_get_select_title, media_search_manager
from .film import download_film from .film import download_film
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
# Variable # Variable
indice = 2 indice = 2
@ -22,33 +21,34 @@ _useFor = "film"
_deprecate = False _deprecate = False
_priority = 2 _priority = 2
_engineDownload = "hls" _engineDownload = "hls"
from .costant import SITE_NAME from .costant import SITE_NAME, TELEGRAM_BOT
def search(string_to_search: str = None, get_onylDatabase: bool = False): def search(string_to_search: str = None, get_onylDatabase: bool = False):
""" """
Main function of the application for film and series. Main function of the application for film and series.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
if string_to_search is None: if string_to_search is None:
# Chiedi la scelta all'utente con il bot Telegram
string_to_search = bot.ask( # Chiedi la scelta all'utente con il bot Telegram
"key_search", string_to_search = bot.ask(
f"Inserisci la parola da cercare\noppure 🔙 back per tornare alla scelta: ", "key_search",
None f"Inserisci la parola da cercare\noppure 🔙 back per tornare alla scelta: ",
) None
)
if string_to_search == 'back':
# Riavvia lo script
# Chiude il processo attuale e avvia una nuova istanza dello script
subprocess.Popen([sys.executable] + sys.argv)
sys.exit()
if string_to_search == 'back':
# Riavvia lo script
# Chiude il processo attuale e avvia una nuova istanza dello script
subprocess.Popen([sys.executable] + sys.argv)
sys.exit()
else: else:
if string_to_search is None: if string_to_search is None:
string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip() string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip()
# Search on database # Search on database
len_database = title_search(quote_plus(string_to_search)) len_database = title_search(quote_plus(string_to_search))
@ -66,9 +66,8 @@ def search(string_to_search: str = None, get_onylDatabase: bool = False):
download_film(select_title) download_film(select_title)
else: else:
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot.send_message(f"Nessun risultato trovato riprova", None) bot.send_message(f"Nessun risultato trovato riprova", None)
console.print(f"\n[red]Nothing matching was found for[white]: [purple]{string_to_search}") console.print(f"\n[red]Nothing matching was found for[white]: [purple]{string_to_search}")

View File

@ -16,4 +16,6 @@ MOVIE_FOLDER = os.path.join(ROOT_PATH, config_manager.get('DEFAULT', 'movie_fold
if config_manager.get_bool("DEFAULT", "add_siteName"): if config_manager.get_bool("DEFAULT", "add_siteName"):
SERIES_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'serie_folder_name')) SERIES_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'serie_folder_name'))
MOVIE_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'movie_folder_name')) MOVIE_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'movie_folder_name'))
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')

View File

@ -1,19 +1,18 @@
# 26.05.24 # 26.05.24
import os import os
import time
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console
from StreamingCommunity.Util.os import os_manager from StreamingCommunity.Util.os import os_manager
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Util.call_stack import get_call_stack
from StreamingCommunity.Lib.Downloader import HLS_Downloader from StreamingCommunity.Lib.Downloader import HLS_Downloader
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
# Logic class # Logic class
from StreamingCommunity.Api.Template.Util import execute_search
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
@ -22,13 +21,7 @@ from StreamingCommunity.Api.Player.supervideo import VideoSource
# Config # Config
from .costant import MOVIE_FOLDER from .costant import MOVIE_FOLDER, TELEGRAM_BOT
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.HelpTg.session import get_session, updateScriptId, deleteScriptId
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
def download_film(select_title: MediaItem) -> str: def download_film(select_title: MediaItem) -> str:
@ -42,17 +35,14 @@ def download_film(select_title: MediaItem) -> str:
Return: Return:
- str: output path - str: output path
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
bot.send_message(f"Download in corso:\n{select_title.name}", None)
# Invio a telegram # Get script_id
bot.send_message(f"Download in corso:\n{select_title.name}", None) script_id = get_session()
if script_id != "unknown":
# Get script_id updateScriptId(script_id, select_title.name)
script_id = get_session()
if script_id != "unknown":
updateScriptId(script_id, select_title.name)
# Start message and display film information # Start message and display film information
start_message() start_message()
@ -71,26 +61,21 @@ def download_film(select_title: MediaItem) -> str:
# Download the film using the m3u8 playlist, and output filename # Download the film using the m3u8 playlist, and output filename
r_proc = HLS_Downloader( r_proc = HLS_Downloader(
m3u8_playlist=master_playlist, m3u8_url=master_playlist,
output_filename=os.path.join(mp4_path, title_name) output_path=os.path.join(mp4_path, title_name)
).start() ).start()
"""if r_proc == 404:
time.sleep(2)
# Re call search function
if msg.ask("[green]Do you want to continue [white]([red]y[white])[green] or return at home[white]([red]n[white]) ", choices=['y', 'n'], default='y', show_choices=True) == "n":
frames = get_call_stack()
execute_search(frames[-4])"""
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Delete script_id
script_id = get_session() # Delete script_id
if script_id != "unknown": script_id = get_session()
deleteScriptId(script_id) if script_id != "unknown":
deleteScriptId(script_id)
if r_proc != None: if "error" in r_proc.keys():
console.print("[green]Result: ") try:
console.print(r_proc) os.remove(r_proc['path'])
except:
pass
return os.path.join(mp4_path, title_name) return r_proc['path']

View File

@ -26,7 +26,7 @@ max_timeout = config_manager.get_int("REQUESTS", "timeout")
disable_searchDomain = config_manager.get_bool("DEFAULT", "disable_searchDomain") disable_searchDomain = config_manager.get_bool("DEFAULT", "disable_searchDomain")
# Telegram bot instance # Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
from StreamingCommunity.Util._jsonConfig import config_manager from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot') TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
@ -42,7 +42,7 @@ def title_search(title_search: str) -> int:
int: The number of titles found. int: The number of titles found.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
media_search_manager.clear() media_search_manager.clear()
table_show_manager.clear() table_show_manager.clear()
@ -71,9 +71,9 @@ def title_search(title_search: str) -> int:
# Create soup and find table # Create soup and find table
soup = BeautifulSoup(response.text, "html.parser") soup = BeautifulSoup(response.text, "html.parser")
# Inizializza la lista delle scelte
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Inizializza la lista delle scelte choices = []
choices = []
for row in soup.find_all('div', class_='col-lg-3 col-md-3 col-xs-4'): for row in soup.find_all('div', class_='col-lg-3 col-md-3 col-xs-4'):
try: try:
@ -94,19 +94,17 @@ def title_search(title_search: str) -> int:
media_search_manager.add_media(film_info) media_search_manager.add_media(film_info)
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Crea una stringa formattata per ogni scelta con numero # Crea una stringa formattata per ogni scelta con numero
choice_text = f"{len(choices)} - {film_info.get('name')} ({film_info.get('url')}) {film_info.get('score')}" choice_text = f"{len(choices)} - {film_info.get('name')} ({film_info.get('url')}) {film_info.get('score')}"
choices.append(choice_text) choices.append(choice_text)
except AttributeError as e: except AttributeError as e:
print(f"Error parsing a film entry: {e}") print(f"Error parsing a film entry: {e}")
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Se ci sono scelte, inviale a Telegram if choices:
if choices: bot.send_message(f"Lista dei risultati:", choices)
# Invio a telegram la lista
bot.send_message(f"Lista dei risultati:", choices)
# Return the number of titles found # Return the number of titles found
return media_search_manager.get_length() return media_search_manager.get_length()

View File

@ -1,23 +1,19 @@
# 21.05.24 # 21.05.24
import sys
import subprocess
from urllib.parse import quote_plus from urllib.parse import quote_plus
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console, msg
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
# Logic class # Logic class
from .site import title_search, run_get_select_title, media_search_manager from .site import title_search, run_get_select_title, media_search_manager
from .film_serie import download_film, download_series from .film_serie import download_film, download_series
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
import sys
import subprocess
# Variable # Variable
indice = 1 indice = 1
@ -25,30 +21,32 @@ _useFor = "anime"
_deprecate = False _deprecate = False
_priority = 2 _priority = 2
_engineDownload = "mp4" _engineDownload = "mp4"
from .costant import SITE_NAME from .costant import SITE_NAME, TELEGRAM_BOT
def search(string_to_search: str = None, get_onylDatabase: bool = False): def search(string_to_search: str = None, get_onylDatabase: bool = False):
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
if string_to_search is None: if string_to_search is None:
# Chiedi la scelta all'utente con il bot Telegram
string_to_search = bot.ask( # Chiedi la scelta all'utente con il bot Telegram
"key_search", string_to_search = bot.ask(
f"Inserisci la parola da cercare\noppure 🔙 back per tornare alla scelta: ", "key_search",
None f"Inserisci la parola da cercare\noppure 🔙 back per tornare alla scelta: ",
) None
)
if string_to_search == 'back':
# Riavvia lo script
# Chiude il processo attuale e avvia una nuova istanza dello script
subprocess.Popen([sys.executable] + sys.argv)
sys.exit()
if string_to_search == 'back':
# Riavvia lo script
# Chiude il processo attuale e avvia una nuova istanza dello script
subprocess.Popen([sys.executable] + sys.argv)
sys.exit()
else: else:
if string_to_search is None: if string_to_search is None:
string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip() string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip()
# Search on database # Search on database
len_database = title_search(string_to_search) len_database = title_search(string_to_search)
@ -69,9 +67,8 @@ def search(string_to_search: str = None, get_onylDatabase: bool = False):
download_series(select_title) download_series(select_title)
else: else:
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot.send_message(f"Nessun risultato trovato riprova", None) bot.send_message(f"Nessun risultato trovato riprova", None)
console.print(f"\n[red]Nothing matching was found for[white]: [purple]{string_to_search}") console.print(f"\n[red]Nothing matching was found for[white]: [purple]{string_to_search}")

View File

@ -16,4 +16,6 @@ ANIME_FOLDER = os.path.join(ROOT_PATH, config_manager.get('DEFAULT', 'anime_fold
if config_manager.get_bool("DEFAULT", "add_siteName"): if config_manager.get_bool("DEFAULT", "add_siteName"):
MOVIE_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'movie_folder_name')) MOVIE_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'movie_folder_name'))
ANIME_FOLDER = os.path.join(ROOT_PATH, config_manager.get('DEFAULT', 'anime_folder_name')) ANIME_FOLDER = os.path.join(ROOT_PATH, config_manager.get('DEFAULT', 'anime_folder_name'))
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')

View File

@ -10,6 +10,8 @@ from StreamingCommunity.Util.console import console, msg
from StreamingCommunity.Util.os import os_manager from StreamingCommunity.Util.os import os_manager
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Lib.Downloader import MP4_downloader from StreamingCommunity.Lib.Downloader import MP4_downloader
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
# Logic class # Logic class
@ -23,14 +25,10 @@ from StreamingCommunity.Api.Player.vixcloud import VideoSourceAnime
# Variable # Variable
from .costant import SITE_NAME, ANIME_FOLDER, MOVIE_FOLDER from .costant import SITE_NAME, ANIME_FOLDER, MOVIE_FOLDER, TELEGRAM_BOT
KILL_HANDLER = bool(False) KILL_HANDLER = bool(False)
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.HelpTg.session import get_session, updateScriptId, deleteScriptId
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_source: VideoSourceAnime) -> tuple[str,bool]: def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_source: VideoSourceAnime) -> tuple[str,bool]:
""" """
@ -44,9 +42,8 @@ def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_so
- bool: kill handler status - bool: kill handler status
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
# Get information about the selected episode # Get information about the selected episode
obj_episode = scrape_serie.get_info_episode(index_select) obj_episode = scrape_serie.get_info_episode(index_select)
@ -57,13 +54,13 @@ def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_so
console.print("[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n") console.print("[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n")
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Invio a telegram bot.send_message(f"Download in corso:\nTitolo:{scrape_serie.series_name}\nEpisodio: {obj_episode.number}", None)
bot.send_message(f"Download in corso:\nTitolo:{scrape_serie.series_name}\nEpisodio: {obj_episode.number}", None)
# Get script_id
script_id = get_session()
if script_id != "unknown":
updateScriptId(script_id, f"{scrape_serie.series_name} - E{obj_episode.number}")
# Get script_id
script_id = get_session()
if script_id != "unknown":
updateScriptId(script_id, f"{scrape_serie.series_name} - E{obj_episode.number}")
# Collect mp4 url # Collect mp4 url
video_source.get_embed(obj_episode.id) video_source.get_embed(obj_episode.id)
@ -72,19 +69,15 @@ def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_so
title_name = f"{scrape_serie.series_name}_EP_{obj_episode.number}.mp4" title_name = f"{scrape_serie.series_name}_EP_{obj_episode.number}.mp4"
if scrape_serie.is_series: if scrape_serie.is_series:
mp4_path = os_manager.get_sanitize_path( mp4_path = os_manager.get_sanitize_path(os.path.join(ANIME_FOLDER, scrape_serie.series_name))
os.path.join(ANIME_FOLDER, scrape_serie.series_name)
)
else: else:
mp4_path = os_manager.get_sanitize_path( mp4_path = os_manager.get_sanitize_path(os.path.join(MOVIE_FOLDER, scrape_serie.series_name))
os.path.join(MOVIE_FOLDER, scrape_serie.series_name)
)
# Create output folder # Create output folder
os_manager.create_path(mp4_path) os_manager.create_path(mp4_path)
# Start downloading # Start downloading
r_proc = MP4_downloader( r_proc = MP4_downloader(
url=str(video_source.src_mp4).strip(), url=str(video_source.src_mp4).strip(),
path=os.path.join(mp4_path, title_name) path=os.path.join(mp4_path, title_name)
@ -109,7 +102,8 @@ def download_series(select_title: MediaItem):
- tv_name (str): The name of the TV series. - tv_name (str): The name of the TV series.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
scrape_serie = ScrapeSerieAnime(SITE_NAME) scrape_serie = ScrapeSerieAnime(SITE_NAME)
video_source = VideoSourceAnime(SITE_NAME) video_source = VideoSourceAnime(SITE_NAME)
@ -121,19 +115,19 @@ def download_series(select_title: MediaItem):
console.print(f"[cyan]Episodes find: [red]{episoded_count}") console.print(f"[cyan]Episodes find: [red]{episoded_count}")
if TELEGRAM_BOT: if TELEGRAM_BOT:
console.print(f"\n[cyan]Insert media [red]index [yellow]or [red](*) [cyan]to download all media [yellow]or [red][1-2] [cyan]or [red][3-*] [cyan]for a range of media") console.print(f"\n[cyan]Insert media [red]index [yellow]or [red](*) [cyan]to download all media [yellow]or [red][1-2] [cyan]or [red][3-*] [cyan]for a range of media")
bot.send_message(f"Episodi trovati: {episoded_count}", None)
# Invio a telegram last_command = bot.ask(
bot.send_message(f"Episodi trovati: {episoded_count}", None) "select_title",
f"Inserisci l'indice del media o (*) per scaricare tutti i media, oppure [1-2] o [3-*] per un intervallo di media.",
None
)
last_command = bot.ask(
"select_title",
f"Inserisci l'indice del media o (*) per scaricare tutti i media, oppure [1-2] o [3-*] per un intervallo di media.",
None
)
else: else:
# Prompt user to select an episode index
last_command = msg.ask("\n[cyan]Insert media [red]index [yellow]or [red](*) [cyan]to download all media [yellow]or [red][1-2] [cyan]or [red][3-*] [cyan]for a range of media") # Prompt user to select an episode index
last_command = msg.ask("\n[cyan]Insert media [red]index [yellow]or [red](*) [cyan]to download all media [yellow]or [red][1-2] [cyan]or [red][3-*] [cyan]for a range of media")
# Manage user selection # Manage user selection
list_episode_select = manage_selection(last_command, episoded_count) list_episode_select = manage_selection(last_command, episoded_count)
@ -151,12 +145,12 @@ def download_series(select_title: MediaItem):
kill_handler= download_episode(i_episode-1, scrape_serie, video_source)[1] kill_handler= download_episode(i_episode-1, scrape_serie, video_source)[1]
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot.send_message(f"Finito di scaricare tutte le serie e episodi", None) bot.send_message(f"Finito di scaricare tutte le serie e episodi", None)
# Get script_id # Get script_id
script_id = get_session() script_id = get_session()
if script_id != "unknown": if script_id != "unknown":
deleteScriptId(script_id) deleteScriptId(script_id)
def download_film(select_title: MediaItem): def download_film(select_title: MediaItem):

View File

@ -12,6 +12,7 @@ from bs4 import BeautifulSoup
from StreamingCommunity.Util.console import console from StreamingCommunity.Util.console import console
from StreamingCommunity.Util._jsonConfig import config_manager from StreamingCommunity.Util._jsonConfig import config_manager
from StreamingCommunity.Util.table import TVShowManager from StreamingCommunity.Util.table import TVShowManager
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
# Logic class # Logic class
@ -19,14 +20,9 @@ from StreamingCommunity.Api.Template import get_select_title
from StreamingCommunity.Api.Template.Util import search_domain from StreamingCommunity.Api.Template.Util import search_domain
from StreamingCommunity.Api.Template.Class.SearchType import MediaManager from StreamingCommunity.Api.Template.Class.SearchType import MediaManager
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
# Variable # Variable
from .costant import SITE_NAME, DOMAIN_NOW from .costant import SITE_NAME, DOMAIN_NOW, TELEGRAM_BOT
media_search_manager = MediaManager() media_search_manager = MediaManager()
table_show_manager = TVShowManager() table_show_manager = TVShowManager()
max_timeout = config_manager.get_int("REQUESTS", "timeout") max_timeout = config_manager.get_int("REQUESTS", "timeout")
@ -109,7 +105,7 @@ def title_search(title: str) -> int:
- int: A number containing the length of media search manager. - int: A number containing the length of media search manager.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
media_search_manager.clear() media_search_manager.clear()
table_show_manager.clear() table_show_manager.clear()
@ -154,9 +150,9 @@ def title_search(title: str) -> int:
except Exception as e: except Exception as e:
console.print(f"Site: {SITE_NAME}, request search error: {e}") console.print(f"Site: {SITE_NAME}, request search error: {e}")
# Inizializza la lista delle scelte
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Inizializza la lista delle scelte choices = []
choices = []
for dict_title in response.json()['records']: for dict_title in response.json()['records']:
try: try:
@ -180,11 +176,10 @@ def title_search(title: str) -> int:
except Exception as e: except Exception as e:
print(f"Error parsing a film entry: {e}") print(f"Error parsing a film entry: {e}")
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Se ci sono scelte, inviale a Telegram if choices:
if choices: bot.send_message(f"Lista dei risultati:", choices)
# Invio a telegram la lista
bot.send_message(f"Lista dei risultati:", choices)
# Return the length of media search manager # Return the length of media search manager
return media_search_manager.get_length() return media_search_manager.get_length()

View File

@ -7,12 +7,10 @@ import os
from StreamingCommunity.Util.console import console from StreamingCommunity.Util.console import console
from StreamingCommunity.Util.os import os_manager from StreamingCommunity.Util.os import os_manager
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Util.call_stack import get_call_stack
from StreamingCommunity.Lib.Downloader import HLS_Downloader from StreamingCommunity.Lib.Downloader import HLS_Downloader
# Logic class # Logic class
from StreamingCommunity.Api.Template.Util import execute_search
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
@ -34,8 +32,6 @@ def download_film(select_title: MediaItem) -> str:
Return: Return:
- str: output path - str: output path
""" """
# Start message and display film information
start_message() start_message()
console.print(f"[yellow]Download: [red]{select_title.name} \n") console.print(f"[yellow]Download: [red]{select_title.name} \n")
console.print(f"[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n") console.print(f"[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n")
@ -53,20 +49,14 @@ def download_film(select_title: MediaItem) -> str:
# Download the film using the m3u8 playlist, and output filename # Download the film using the m3u8 playlist, and output filename
r_proc = HLS_Downloader( r_proc = HLS_Downloader(
m3u8_playlist=master_playlist, m3u8_url=master_playlist,
output_filename=os.path.join(mp4_path, title_name) output_path=os.path.join(mp4_path, title_name)
).start() ).start()
"""if r_proc == 404: if "error" in r_proc.keys():
time.sleep(2) try:
os.remove(r_proc['path'])
except:
pass
# Re call search function return r_proc['path']
if msg.ask("[green]Do you want to continue [white]([red]y[white])[green] or return at home[white]([red]n[white]) ", choices=['y', 'n'], default='y', show_choices=True) == "n":
frames = get_call_stack()
execute_search(frames[-4])"""
if r_proc != None:
console.print("[green]Result: ")
console.print(r_proc)
return os.path.join(mp4_path, title_name)

View File

@ -7,13 +7,12 @@ import sys
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console, msg
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Util.call_stack import get_call_stack
from StreamingCommunity.Util.table import TVShowManager from StreamingCommunity.Util.table import TVShowManager
from StreamingCommunity.Lib.Downloader import HLS_Downloader from StreamingCommunity.Lib.Downloader import HLS_Downloader
# Logic class # Logic class
from StreamingCommunity.Api.Template.Util import manage_selection, map_episode_title, dynamic_format_number, validate_selection, validate_episode_selection, execute_search from StreamingCommunity.Api.Template.Util import manage_selection, map_episode_title, dynamic_format_number, validate_selection, validate_episode_selection
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
@ -46,6 +45,7 @@ def download_video(index_season_selected: int, index_episode_selected: int, scap
obj_episode = scape_info_serie.list_episodes[index_episode_selected - 1] obj_episode = scape_info_serie.list_episodes[index_episode_selected - 1]
console.print(f"[yellow]Download: [red]{index_season_selected}:{index_episode_selected} {obj_episode.get('name')}\n") console.print(f"[yellow]Download: [red]{index_season_selected}:{index_episode_selected} {obj_episode.get('name')}\n")
console.print(f"[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n") console.print(f"[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n")
# Define filename and path for the downloaded video # Define filename and path for the downloaded video
mp4_name = f"{map_episode_title(scape_info_serie.tv_name, index_season_selected, index_episode_selected, obj_episode.get('name'))}.mp4" mp4_name = f"{map_episode_title(scape_info_serie.tv_name, index_season_selected, index_episode_selected, obj_episode.get('name'))}.mp4"
mp4_path = os.path.join(SERIES_FOLDER, scape_info_serie.tv_name, f"S{index_season_selected}") mp4_path = os.path.join(SERIES_FOLDER, scape_info_serie.tv_name, f"S{index_season_selected}")
@ -58,23 +58,18 @@ def download_video(index_season_selected: int, index_episode_selected: int, scap
# Download the film using the m3u8 playlist, and output filename # Download the film using the m3u8 playlist, and output filename
r_proc = HLS_Downloader( r_proc = HLS_Downloader(
m3u8_playlist=master_playlist, m3u8_url=master_playlist,
output_filename=os.path.join(mp4_path, mp4_name) output_path=os.path.join(mp4_path, mp4_name)
).start() ).start()
"""if r_proc == 404:
time.sleep(2)
# Re call search function
if msg.ask("[green]Do you want to continue [white]([red]y[white])[green] or return at home[white]([red]n[white]) ", choices=['y', 'n'], default='y', show_choices=True) == "n":
frames = get_call_stack()
execute_search(frames[-4])"""
if r_proc != None: if "error" in r_proc.keys():
console.print("[green]Result: ") try:
console.print(r_proc) os.remove(r_proc['path'])
except:
pass
return os.path.join(mp4_path, mp4_name) return r_proc['path'], r_proc['stopped']
def download_episode(scape_info_serie: GetSerieInfo, index_season_selected: int, download_all: bool = False) -> None: def download_episode(scape_info_serie: GetSerieInfo, index_season_selected: int, download_all: bool = False) -> None:
@ -96,7 +91,11 @@ def download_episode(scape_info_serie: GetSerieInfo, index_season_selected: int,
# Download all episodes without asking # Download all episodes without asking
for i_episode in range(1, episodes_count + 1): for i_episode in range(1, episodes_count + 1):
download_video(index_season_selected, i_episode, scape_info_serie) path, stopped = download_video(index_season_selected, i_episode, scape_info_serie)
if stopped:
break
console.print(f"\n[red]End downloaded [yellow]season: [red]{index_season_selected}.") console.print(f"\n[red]End downloaded [yellow]season: [red]{index_season_selected}.")
else: else:
@ -112,11 +111,11 @@ def download_episode(scape_info_serie: GetSerieInfo, index_season_selected: int,
return return
# Download selected episodes # Download selected episodes
stopped = bool(False)
for i_episode in list_episode_select: for i_episode in list_episode_select:
path, stopped = download_video(index_season_selected, i_episode, scape_info_serie)
if stopped: if stopped:
break break
download_video(index_season_selected, i_episode, scape_info_serie)
def download_series(dict_serie: MediaItem) -> None: def download_series(dict_serie: MediaItem) -> None:
@ -197,4 +196,4 @@ def display_episodes_list(obj_episode_manager) -> str:
console.print("\n[red]Quit [white]...") console.print("\n[red]Quit [white]...")
sys.exit(0) sys.exit(0)
return last_command return last_command

View File

@ -2,7 +2,6 @@
import os import os
import sys import sys
import time
import logging import logging
@ -12,18 +11,13 @@ from bs4 import BeautifulSoup
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console
from StreamingCommunity.Util.os import os_manager from StreamingCommunity.Util.os import os_manager
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Util.call_stack import get_call_stack
from StreamingCommunity.Util.headers import get_headers from StreamingCommunity.Util.headers import get_headers
from StreamingCommunity.Lib.Downloader import HLS_Downloader from StreamingCommunity.Lib.Downloader import HLS_Downloader
# Logic class
from StreamingCommunity.Api.Template.Util import execute_search
# Player # Player
from StreamingCommunity.Api.Player.supervideo import VideoSource from StreamingCommunity.Api.Player.supervideo import VideoSource
@ -51,6 +45,7 @@ def download_film(movie_details: Json_film) -> str:
start_message() start_message()
console.print(f"[yellow]Download: [red]{movie_details.title} \n") console.print(f"[yellow]Download: [red]{movie_details.title} \n")
console.print(f"[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n") console.print(f"[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n")
# Make request to main site # Make request to main site
try: try:
url = f"https://{SITE_NAME}.{DOMAIN_NOW}/set-movie-a/{movie_details.imdb_id}" url = f"https://{SITE_NAME}.{DOMAIN_NOW}/set-movie-a/{movie_details.imdb_id}"
@ -82,20 +77,14 @@ def download_film(movie_details: Json_film) -> str:
# Download the film using the m3u8 playlist, and output filename # Download the film using the m3u8 playlist, and output filename
r_proc = HLS_Downloader( r_proc = HLS_Downloader(
m3u8_playlist=master_playlist, m3u8_url=master_playlist,
output_filename=os.path.join(mp4_path, title_name) output_path=os.path.join(mp4_path, title_name)
).start() ).start()
"""if r_proc == 404: if "error" in r_proc.keys():
time.sleep(2) try:
os.remove(r_proc['path'])
except:
pass
# Re call search function return r_proc['path']
if msg.ask("[green]Do you want to continue [white]([red]y[white])[green] or return at home[white]([red]n[white]) ", choices=['y', 'n'], default='y', show_choices=True) == "n":
frames = get_call_stack()
execute_search(frames[-4])"""
if r_proc != None:
console.print("[green]Result: ")
console.print(r_proc)
return os.path.join(mp4_path, title_name)

View File

@ -1,11 +1,13 @@
# 21.05.24 # 21.05.24
from urllib.parse import quote_plus
import subprocess
import sys import sys
import subprocess
from urllib.parse import quote_plus
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console, msg
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
# Logic class # Logic class
@ -13,10 +15,6 @@ from .site import get_version_and_domain, title_search, run_get_select_title, me
from .film import download_film from .film import download_film
from .series import download_series from .series import download_series
# Telegram bot instance
from StreamingCommunity.Util._jsonConfig import config_manager
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
# Variable # Variable
indice = 0 indice = 0
@ -24,30 +22,31 @@ _useFor = "film_serie"
_deprecate = False _deprecate = False
_priority = 1 _priority = 1
_engineDownload = "hls" _engineDownload = "hls"
from .costant import SITE_NAME from .costant import SITE_NAME, TELEGRAM_BOT
def search(string_to_search: str = None, get_onylDatabase: bool = False): def search(string_to_search: str = None, get_onylDatabase: bool = False):
""" """
Main function of the application for film and series. Main function of the application for film and series.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
if string_to_search is None: if string_to_search is None:
# Chiedi la scelta all'utente con il bot Telegram
string_to_search = bot.ask( # Chiedi la scelta all'utente con il bot Telegram
"key_search", string_to_search = bot.ask(
f"Inserisci la parola da cercare\noppure 🔙 back per tornare alla scelta: ", "key_search",
None f"Inserisci la parola da cercare\noppure 🔙 back per tornare alla scelta: ",
) None
)
if string_to_search == 'back': if string_to_search == 'back':
# Riavvia lo script # Riavvia lo script
# Chiude il processo attuale e avvia una nuova istanza dello script # Chiude il processo attuale e avvia una nuova istanza dello script
subprocess.Popen([sys.executable] + sys.argv) subprocess.Popen([sys.executable] + sys.argv)
sys.exit() sys.exit()
else: else:
if string_to_search is None: if string_to_search is None:
string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip() string_to_search = msg.ask(f"\n[purple]Insert word to search in [green]{SITE_NAME}").strip()

View File

@ -16,4 +16,6 @@ MOVIE_FOLDER = os.path.join(ROOT_PATH, config_manager.get('DEFAULT', 'movie_fold
if config_manager.get_bool("DEFAULT", "add_siteName"): if config_manager.get_bool("DEFAULT", "add_siteName"):
SERIES_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'serie_folder_name')) SERIES_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'serie_folder_name'))
MOVIE_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'movie_folder_name')) MOVIE_FOLDER = os.path.join(ROOT_PATH, SITE_NAME, config_manager.get('DEFAULT', 'movie_folder_name'))
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')

View File

@ -1,19 +1,18 @@
# 3.12.23 # 3.12.23
import os import os
import time
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console
from StreamingCommunity.Util.os import os_manager from StreamingCommunity.Util.os import os_manager
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Util.call_stack import get_call_stack
from StreamingCommunity.Lib.Downloader import HLS_Downloader from StreamingCommunity.Lib.Downloader import HLS_Downloader
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
# Logic class # Logic class
from StreamingCommunity.Api.Template.Util import execute_search
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
@ -22,13 +21,7 @@ from StreamingCommunity.Api.Player.vixcloud import VideoSource
# Variable # Variable
from .costant import SITE_NAME, MOVIE_FOLDER from .costant import SITE_NAME, MOVIE_FOLDER, TELEGRAM_BOT
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.HelpTg.session import get_session, updateScriptId, deleteScriptId
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
def download_film(select_title: MediaItem) -> str: def download_film(select_title: MediaItem) -> str:
@ -43,18 +36,16 @@ def download_film(select_title: MediaItem) -> str:
- str: output path - str: output path
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
bot.send_message(f"Download in corso:\n{select_title.name}", None)
# Invio a telegram
bot.send_message(f"Download in corso:\n{select_title.name}", None)
# Viene usato per lo screen # Viene usato per lo screen
console.print(f"## Download: [red]{select_title.name} ##") console.print(f"## Download: [red]{select_title.name} ##")
# Get script_id # Get script_id
script_id = get_session() script_id = get_session()
if script_id != "unknown": if script_id != "unknown":
updateScriptId(script_id, select_title.name) updateScriptId(script_id, select_title.name)
# Start message and display film information # Start message and display film information
start_message() start_message()
@ -75,26 +66,21 @@ def download_film(select_title: MediaItem) -> str:
# Download the film using the m3u8 playlist, and output filename # Download the film using the m3u8 playlist, and output filename
r_proc = HLS_Downloader( r_proc = HLS_Downloader(
m3u8_playlist=master_playlist, m3u8_url=master_playlist,
output_filename=os.path.join(mp4_path, title_name) output_path=os.path.join(mp4_path, title_name)
).start() ).start()
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Delete script_id
script_id = get_session() # Delete script_id
if script_id != "unknown": script_id = get_session()
deleteScriptId(script_id) if script_id != "unknown":
deleteScriptId(script_id)
"""if r_proc == 404: if "error" in r_proc.keys():
time.sleep(2) try:
os.remove(r_proc['path'])
except:
pass
# Re call search function return r_proc['path']
if msg.ask("[green]Do you want to continue [white]([red]y[white])[green] or return at home[white]([red]n[white]) ", choices=['y', 'n'], default='y', show_choices=True) == "n":
frames = get_call_stack()
execute_search(frames[-4])"""
if r_proc != None:
console.print("[green]Result: ")
console.print(r_proc)
return os.path.join(mp4_path, title_name)

View File

@ -2,20 +2,20 @@
import os import os
import sys import sys
import time
# Internal utilities # Internal utilities
from StreamingCommunity.Util.console import console, msg from StreamingCommunity.Util.console import console, msg
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Util.call_stack import get_call_stack
from StreamingCommunity.Util.table import TVShowManager from StreamingCommunity.Util.table import TVShowManager
from StreamingCommunity.Lib.Downloader import HLS_Downloader from StreamingCommunity.Lib.Downloader import HLS_Downloader
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
from StreamingCommunity.TelegramHelp.session import get_session, updateScriptId, deleteScriptId
# Logic class # Logic class
from .util.ScrapeSerie import ScrapeSerie from .util.ScrapeSerie import ScrapeSerie
from StreamingCommunity.Api.Template.Util import manage_selection, map_episode_title, dynamic_format_number, validate_selection, validate_episode_selection, execute_search from StreamingCommunity.Api.Template.Util import manage_selection, map_episode_title, dynamic_format_number, validate_selection, validate_episode_selection
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
@ -24,13 +24,7 @@ from StreamingCommunity.Api.Player.vixcloud import VideoSource
# Variable # Variable
from .costant import SITE_NAME, SERIES_FOLDER from .costant import SITE_NAME, SERIES_FOLDER, TELEGRAM_BOT
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
from StreamingCommunity.HelpTg.session import get_session, updateScriptId, deleteScriptId
from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
def download_video(index_season_selected: int, index_episode_selected: int, scrape_serie: ScrapeSerie, video_source: VideoSource) -> tuple[str,bool]: def download_video(index_season_selected: int, index_episode_selected: int, scrape_serie: ScrapeSerie, video_source: VideoSource) -> tuple[str,bool]:
@ -54,18 +48,17 @@ def download_video(index_season_selected: int, index_episode_selected: int, scra
print() print()
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
# Invio a telegram # Invio a telegram
bot.send_message( bot.send_message(
f"Download in corso\nSerie: {scrape_serie.series_name}\nStagione: {index_season_selected}\nEpisodio: {index_episode_selected}\nTitolo: {obj_episode.name}", f"Download in corso\nSerie: {scrape_serie.series_name}\nStagione: {index_season_selected}\nEpisodio: {index_episode_selected}\nTitolo: {obj_episode.name}",
None None
) )
# Get script_id # Get script_id and update it
script_id = get_session() script_id = get_session()
if script_id != "unknown": if script_id != "unknown":
# Update script_id
updateScriptId(script_id, f"{scrape_serie.series_name} - S{index_season_selected} - E{index_episode_selected} - {obj_episode.name}") updateScriptId(script_id, f"{scrape_serie.series_name} - S{index_season_selected} - E{index_episode_selected} - {obj_episode.name}")
# Define filename and path for the downloaded video # Define filename and path for the downloaded video
@ -79,26 +72,17 @@ def download_video(index_season_selected: int, index_episode_selected: int, scra
# Download the episode # Download the episode
r_proc = HLS_Downloader( r_proc = HLS_Downloader(
m3u8_playlist=master_playlist, m3u8_url=master_playlist,
output_filename=os.path.join(mp4_path, mp4_name) output_path=os.path.join(mp4_path, mp4_name)
).start() ).start()
#bot.send_message(f"Serie scaricata tutta", None) if "error" in r_proc.keys():
try:
os.remove(r_proc['path'])
except:
pass
"""if r_proc == 404: return r_proc['path'], r_proc['stopped']
time.sleep(2)
# Re call search function
if msg.ask("[green]Do you want to continue [white]([red]y[white])[green] or return at home[white]([red]n[white]) ", choices=['y', 'n'], default='y', show_choices=True) == "n":
frames = get_call_stack()
execute_search(frames[-4])"""
if r_proc != None:
console.print("[green]Result: ")
console.print(r_proc)
#bot.send_message(f"Episodio scaricato", None)
return os.path.join(mp4_path, mp4_name)
def download_episode(index_season_selected: int, scrape_serie: ScrapeSerie, video_source: VideoSource, download_all: bool = False) -> None: def download_episode(index_season_selected: int, scrape_serie: ScrapeSerie, video_source: VideoSource, download_all: bool = False) -> None:
""" """
@ -109,8 +93,6 @@ def download_episode(index_season_selected: int, scrape_serie: ScrapeSerie, vide
- download_all (bool): Download all episodes in the season. - download_all (bool): Download all episodes in the season.
""" """
#bot = get_bot_instance()
# Clean memory of all episodes and get the number of the season # Clean memory of all episodes and get the number of the season
scrape_serie.episode_manager.clear() scrape_serie.episode_manager.clear()
@ -123,10 +105,12 @@ def download_episode(index_season_selected: int, scrape_serie: ScrapeSerie, vide
# Download all episodes without asking # Download all episodes without asking
for i_episode in range(1, episodes_count + 1): for i_episode in range(1, episodes_count + 1):
download_video(index_season_selected, i_episode, scrape_serie, video_source) path, stopped = download_video(index_season_selected, i_episode, scrape_serie, video_source)
console.print(f"\n[red]End downloaded [yellow]season: [red]{index_season_selected}.")
#bot.send_message(f"Finito di scaricare la stagione: {index_season_selected}", None) if stopped:
break
console.print(f"\n[red]End downloaded [yellow]season: [red]{index_season_selected}.")
else: else:
@ -138,15 +122,14 @@ def download_episode(index_season_selected: int, scrape_serie: ScrapeSerie, vide
list_episode_select = validate_episode_selection(list_episode_select, episodes_count) list_episode_select = validate_episode_selection(list_episode_select, episodes_count)
except ValueError as e: except ValueError as e:
console.print(f"[red]{str(e)}") console.print(f"[red]{str(e)}")
#bot.send_message(f"{str(e)}", None)
return return
# Download selected episodes if not stopped # Download selected episodes if not stopped
stopped = bool(False)
for i_episode in list_episode_select: for i_episode in list_episode_select:
path, stopped = download_video(index_season_selected, i_episode, scrape_serie, video_source)
if stopped: if stopped:
break break
stopped=download_video(index_season_selected, i_episode, scrape_serie, video_source)[1]
def download_series(select_season: MediaItem, version: str) -> None: def download_series(select_season: MediaItem, version: str) -> None:
""" """
@ -158,7 +141,7 @@ def download_series(select_season: MediaItem, version: str) -> None:
- version (str): Version of the site. - version (str): Version of the site.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
# Start message and set up video source # Start message and set up video source
start_message() start_message()
@ -179,21 +162,22 @@ def download_series(select_season: MediaItem, version: str) -> None:
console.print(f"\n[green]Seasons found: [red]{seasons_count}") console.print(f"\n[green]Seasons found: [red]{seasons_count}")
if TELEGRAM_BOT: if TELEGRAM_BOT:
console.print("\n[cyan]Insert season number [yellow](e.g., 1), [red]* [cyan]to download all seasons, " console.print("\n[cyan]Insert season number [yellow](e.g., 1), [red]* [cyan]to download all seasons, "
"[yellow](e.g., 1-2) [cyan]for a range of seasons, or [yellow](e.g., 3-*) [cyan]to download from a specific season to the end") "[yellow](e.g., 1-2) [cyan]for a range of seasons, or [yellow](e.g., 3-*) [cyan]to download from a specific season to the end")
bot.send_message(f"Stagioni trovate: {seasons_count}", None) bot.send_message(f"Stagioni trovate: {seasons_count}", None)
index_season_selected = bot.ask(
"select_title_episode",
"Inserisci il numero della stagione (es. 1), * per scaricare tutte le stagioni, (es. 1-2) per un intervallo di stagioni, o (es. 3-*) per scaricare dalla stagione specificata fino alla fine",
None
)
index_season_selected = bot.ask(
"select_title_episode",
"Inserisci il numero della stagione (es. 1), * per scaricare tutte le stagioni, (es. 1-2) per un intervallo di stagioni, o (es. 3-*) per scaricare dalla stagione specificata fino alla fine",
None
)
else: else:
index_season_selected = msg.ask( index_season_selected = msg.ask(
"\n[cyan]Insert season number [yellow](e.g., 1), [red]* [cyan]to download all seasons, " "\n[cyan]Insert season number [yellow](e.g., 1), [red]* [cyan]to download all seasons, "
"[yellow](e.g., 1-2) [cyan]for a range of seasons, or [yellow](e.g., 3-*) [cyan]to download from a specific season to the end" "[yellow](e.g., 1-2) [cyan]for a range of seasons, or [yellow](e.g., 3-*) [cyan]to download from a specific season to the end"
) )
# Manage and validate the selection # Manage and validate the selection
list_season_select = manage_selection(index_season_selected, seasons_count) list_season_select = manage_selection(index_season_selected, seasons_count)
@ -216,11 +200,12 @@ def download_series(select_season: MediaItem, version: str) -> None:
download_episode(i_season, scrape_serie, video_source, download_all=False) download_episode(i_season, scrape_serie, video_source, download_all=False)
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot.send_message(f"Finito di scaricare tutte le serie e episodi", None) bot.send_message(f"Finito di scaricare tutte le serie e episodi", None)
# Get script_id
script_id = get_session() # Get script_id
if script_id != "unknown": script_id = get_session()
deleteScriptId(script_id) if script_id != "unknown":
deleteScriptId(script_id)
def display_episodes_list(scrape_serie) -> str: def display_episodes_list(scrape_serie) -> str:
@ -231,7 +216,7 @@ def display_episodes_list(scrape_serie) -> str:
last_command (str): Last command entered by the user. last_command (str): Last command entered by the user.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
# Set up table for displaying episodes # Set up table for displaying episodes
table_show_manager = TVShowManager() table_show_manager = TVShowManager()
@ -247,7 +232,8 @@ def display_episodes_list(scrape_serie) -> str:
# Populate the table with episodes information # Populate the table with episodes information
if TELEGRAM_BOT: if TELEGRAM_BOT:
choices = [] choices = []
for i, media in enumerate(scrape_serie.episode_manager.episodes): for i, media in enumerate(scrape_serie.episode_manager.episodes):
table_show_manager.add_tv_show({ table_show_manager.add_tv_show({
'Index': str(media.number), 'Index': str(media.number),
@ -256,20 +242,12 @@ def display_episodes_list(scrape_serie) -> str:
}) })
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Creazione della stringa per il messaggio Telegram choice_text = f"{media.number} - {media.name} ({media.duration} min)"
choice_text = f"{media.number} - {media.name} ({media.duration} min)" choices.append(choice_text)
choices.append(choice_text)
if TELEGRAM_BOT: if TELEGRAM_BOT:
# creo episoded_count if choices:
#episoded_count = len(scrape_serie.episode_manager.episodes) bot.send_message(f"Lista episodi:", choices)
# Invio a telegram
#bot.send_message(f"Episodi trovati: {episoded_count}", None)
# Invia la lista degli episodi al bot Telegram
if choices:
bot.send_message(f"Lista episodi:", choices)
# Run the table and handle user input # Run the table and handle user input
last_command = table_show_manager.run() last_command = table_show_manager.run()
@ -278,4 +256,4 @@ def display_episodes_list(scrape_serie) -> str:
console.print("\n[red]Quit [white]...") console.print("\n[red]Quit [white]...")
sys.exit(0) sys.exit(0)
return last_command return last_command

View File

@ -15,7 +15,7 @@ from StreamingCommunity.Util.console import console
from StreamingCommunity.Util._jsonConfig import config_manager from StreamingCommunity.Util._jsonConfig import config_manager
from StreamingCommunity.Util.headers import get_headers from StreamingCommunity.Util.headers import get_headers
from StreamingCommunity.Util.table import TVShowManager from StreamingCommunity.Util.table import TVShowManager
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
# Logic class # Logic class
@ -25,11 +25,8 @@ from StreamingCommunity.Api.Template.Class.SearchType import MediaManager
# Config # Config
from .costant import SITE_NAME, DOMAIN_NOW from .costant import SITE_NAME, DOMAIN_NOW, TELEGRAM_BOT
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
# Variable # Variable
media_search_manager = MediaManager() media_search_manager = MediaManager()
@ -123,13 +120,12 @@ def title_search(title_search: str, domain: str) -> int:
except Exception as e: except Exception as e:
console.print(f"Site: {SITE_NAME}, request search error: {e}") console.print(f"Site: {SITE_NAME}, request search error: {e}")
# Prepara le scelte per l'utente
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Prepara le scelte per l'utente choices = []
choices = []
for i, dict_title in enumerate(response.json()['data']): for i, dict_title in enumerate(response.json()['data']):
try: try:
media_search_manager.add_media({ media_search_manager.add_media({
'id': dict_title.get('id'), 'id': dict_title.get('id'),
'slug': dict_title.get('slug'), 'slug': dict_title.get('slug'),
@ -138,18 +134,17 @@ def title_search(title_search: str, domain: str) -> int:
'date': dict_title.get('last_air_date'), 'date': dict_title.get('last_air_date'),
'score': dict_title.get('score') 'score': dict_title.get('score')
}) })
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Crea una stringa formattata per ogni scelta con numero choice_text = f"{i} - {dict_title.get('name')} ({dict_title.get('type')}) - {dict_title.get('last_air_date')}"
choice_text = f"{i} - {dict_title.get('name')} ({dict_title.get('type')}) - {dict_title.get('last_air_date')}" choices.append(choice_text)
choices.append(choice_text)
except Exception as e: except Exception as e:
print(f"Error parsing a film entry: {e}") print(f"Error parsing a film entry: {e}")
if TELEGRAM_BOT: if TELEGRAM_BOT:
if choices: if choices:
# Invio a telegram la lista bot.send_message(f"Lista dei risultati:", choices)
bot.send_message(f"Lista dei risultati:", choices)
# Return the number of titles found # Return the number of titles found
return media_search_manager.get_length() return media_search_manager.get_length()

View File

@ -1,91 +0,0 @@
{
"DEFAULT": {
"debug": false,
"log_file": "app.log",
"log_to_file": true,
"show_message": true,
"clean_console": true,
"root_path": "Video",
"movie_folder_name": "Movie",
"serie_folder_name": "TV",
"anime_folder_name": "Anime",
"map_episode_name": "E%(episode)_%(episode_name)",
"config_qbit_tor": {
"host": "192.168.1.99",
"port": "7060",
"user": "admin",
"pass": "adminadmin"
},
"add_siteName": false,
"disable_searchDomain": false,
"not_close": false,
"telegram_bot": true
},
"REQUESTS": {
"timeout": 30,
"max_retry": 8,
"proxy_start_min": 0.1,
"proxy_start_max": 0.5
},
"M3U8_DOWNLOAD": {
"tqdm_delay": 0.12,
"default_video_workser": 12,
"default_audio_workser": 12,
"merge_audio": true,
"specific_list_audio": [
"ita"
],
"merge_subs": false,
"specific_list_subtitles": [
"eng",
"spa"
],
"cleanup_tmp_folder": true
},
"M3U8_CONVERSION": {
"use_codec": false,
"use_vcodec": true,
"use_acodec": true,
"use_bitrate": true,
"use_gpu": false,
"default_preset": "ultrafast"
},
"M3U8_PARSER": {
"force_resolution": -1,
"get_only_link": false
},
"SITE": {
"streamingcommunity": {
"domain": "paris"
},
"altadefinizionegratis": {
"domain": "site"
},
"guardaserie": {
"domain": "meme"
},
"mostraguarda": {
"domain": "stream"
},
"ddlstreamitaly": {
"domain": "co",
"extra": {
"ips4_device_key": "",
"ips4_member_id": "",
"ips4_login_key": ""
}
},
"animeunity": {
"domain": "so"
},
"cb01new": {
"domain": "mobi"
},
"1337xx": {
"domain": "to"
},
"ilcorsaronero": {
"domain": "link"
}
}
}

View File

@ -1,79 +0,0 @@
import json
import time
from typing import Optional
class RequestManager:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, json_file: str = "active_requests.json"):
if not hasattr(self, 'initialized'):
self.json_file = json_file
self.initialized = True
self.on_response_callback = None # Aggiungi un campo per il callback
def create_request(self, type: str) -> str:
request_data = {
"type": type,
"response": None,
"timestamp": time.time()
}
# Aggiungi il tipo al salvataggio della richiesta
with open(self.json_file, "w") as f:
json.dump(request_data, f)
return "Ok"
def save_response(self, message_text: str) -> bool:
try:
# Carica il file JSON
with open(self.json_file, "r") as f:
data = json.load(f)
# Controlla se esiste la chiave 'type' e se la risposta è presente
if "type" in data and "response" in data:
data["response"] = message_text # Aggiorna la risposta
# Scrivi il file JSON aggiornato
with open(self.json_file, "w") as f:
json.dump(data, f, indent=4) # Formatta il file JSON
return True
else:
return False
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"⚠️ save_response - errore: {e}")
return False
def get_response(self) -> Optional[str]:
try:
with open(self.json_file, "r") as f:
data = json.load(f)
# Verifica se esiste la chiave "response"
if "response" in data:
response = data["response"] # Ottieni la risposta direttamente
if response is not None and self.on_response_callback:
# Se la risposta è disponibile, chiama il callback
self.on_response_callback(response)
return response
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"get_response - errore: {e}")
return None
def clear_file(self) -> bool:
try:
# Svuota il file JSON scrivendo un oggetto vuoto
with open(self.json_file, "w") as f:
json.dump({}, f)
print(f"File {self.json_file} è stato svuotato con successo.")
return True
except Exception as e:
print(f"⚠️ clear_file - errore: {e}")
return False

View File

@ -1,14 +0,0 @@
httpx
bs4
rich
tqdm
m3u8
psutil
unidecode
jsbeautifier
pathvalidate
pycryptodomex
googlesearch-python
fake-useragent
qbittorrent-api
python-qbittorrent

File diff suppressed because it is too large Load Diff

View File

@ -47,7 +47,6 @@ PROXY_START_MAX = config_manager.get_float('REQUESTS', 'proxy_start_max')
DEFAULT_VIDEO_WORKERS = config_manager.get_int('M3U8_DOWNLOAD', 'default_video_workser') DEFAULT_VIDEO_WORKERS = config_manager.get_int('M3U8_DOWNLOAD', 'default_video_workser')
DEFAULT_AUDIO_WORKERS = config_manager.get_int('M3U8_DOWNLOAD', 'default_audio_workser') DEFAULT_AUDIO_WORKERS = config_manager.get_int('M3U8_DOWNLOAD', 'default_audio_workser')
MAX_TIMEOOUT = config_manager.get_int("REQUESTS", "timeout") MAX_TIMEOOUT = config_manager.get_int("REQUESTS", "timeout")
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
@ -70,7 +69,7 @@ class M3U8_Segments:
# Util class # Util class
self.decryption: M3U8_Decryption = None self.decryption: M3U8_Decryption = None
self.class_ts_estimator = M3U8_Ts_Estimator(0) self.class_ts_estimator = M3U8_Ts_Estimator(0, self)
self.class_url_fixer = M3U8_UrlFix(url) self.class_url_fixer = M3U8_UrlFix(url)
# Sync # Sync
@ -88,6 +87,8 @@ class M3U8_Segments:
self.info_maxRetry = 0 self.info_maxRetry = 0
self.info_nRetry = 0 self.info_nRetry = 0
self.info_nFailed = 0 self.info_nFailed = 0
self.active_retries = 0
self.active_retries_lock = threading.Lock()
def __get_key__(self, m3u8_parser: M3U8_Parser) -> bytes: def __get_key__(self, m3u8_parser: M3U8_Parser) -> bytes:
key_uri = urljoin(self.url, m3u8_parser.keys.get('uri')) key_uri = urljoin(self.url, m3u8_parser.keys.get('uri'))
@ -232,10 +233,17 @@ class M3U8_Segments:
self.queue.put((index, None)) # Marker for failed segment self.queue.put((index, None)) # Marker for failed segment
progress_bar.update(1) progress_bar.update(1)
self.info_nFailed += 1 self.info_nFailed += 1
return
with self.active_retries_lock:
self.active_retries += 1
sleep_time = backoff_factor * (2 ** attempt) sleep_time = backoff_factor * (2 ** attempt)
logging.info(f"Retrying segment {index} in {sleep_time} seconds...") logging.info(f"Retrying segment {index} in {sleep_time} seconds...")
time.sleep(sleep_time) time.sleep(sleep_time)
with self.active_retries_lock:
self.active_retries -= 1
def write_segments_to_file(self): def write_segments_to_file(self):
""" """
@ -296,11 +304,7 @@ class M3U8_Segments:
- description: Description to insert on tqdm bar - description: Description to insert on tqdm bar
- type (str): Type of download: 'video' or 'audio' - type (str): Type of download: 'video' or 'audio'
""" """
self.get_info()
if TELEGRAM_BOT:
# Viene usato per lo screen
console.log("####")
self.setup_interrupt_handler() self.setup_interrupt_handler()
progress_bar = tqdm( progress_bar = tqdm(

View File

@ -1,12 +1,11 @@
# 09.06.24 # 09.06.24
import os import os
import signal, re import re
import sys import sys
import ssl import signal
import certifi
import logging import logging
import atexit
# External libraries # External libraries
import httpx import httpx
@ -19,6 +18,7 @@ from StreamingCommunity.Util.color import Colors
from StreamingCommunity.Util.console import console, Panel from StreamingCommunity.Util.console import console, Panel
from StreamingCommunity.Util._jsonConfig import config_manager from StreamingCommunity.Util._jsonConfig import config_manager
from StreamingCommunity.Util.os import internet_manager from StreamingCommunity.Util.os import internet_manager
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
# Logic class # Logic class
@ -29,16 +29,15 @@ from ...FFmpeg import print_duration_table
import urllib3 import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
# Config # Config
GET_ONLY_LINK = config_manager.get_bool('M3U8_PARSER', 'get_only_link') GET_ONLY_LINK = config_manager.get_bool('M3U8_PARSER', 'get_only_link')
TQDM_USE_LARGE_BAR = not ("android" in sys.platform or "ios" in sys.platform) TQDM_USE_LARGE_BAR = not ("android" in sys.platform or "ios" in sys.platform)
REQUEST_TIMEOUT = config_manager.get_float('REQUESTS', 'timeout') REQUEST_TIMEOUT = config_manager.get_float('REQUESTS', 'timeout')
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
#Ending constant #Ending constant
KILL_HANDLER = bool(False) KILL_HANDLER = bool(False)
@ -54,14 +53,13 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
- headers_ (dict, optional): Custom headers for the request. - headers_ (dict, optional): Custom headers for the request.
""" """
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
# Viene usato per lo screen console.log("####")
console.log("####")
if os.path.exists(path): if os.path.exists(path):
console.log("[red]Output file already exists.") console.log("[red]Output file already exists.")
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot.send_message(f"Contenuto già scaricato!", None) bot.send_message(f"Contenuto già scaricato!", None)
return 400 return 400
# Early return for link-only mode # Early return for link-only mode
@ -94,8 +92,8 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
try: try:
# Create a custom transport that bypasses SSL verification # Create a custom transport that bypasses SSL verification
transport = httpx.HTTPTransport( transport = httpx.HTTPTransport(
verify=False, # Disable SSL certificate verification verify=False,
http2=True # Optional: enable HTTP/2 support http2=True
) )
# Download with streaming and progress tracking # Download with streaming and progress tracking
@ -137,7 +135,6 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
Parameters: Parameters:
- args (tuple): The signal arguments (to prevent errors). - args (tuple): The signal arguments (to prevent errors).
""" """
if(downloaded<total/2): if(downloaded<total/2):
raise KeyboardInterrupt raise KeyboardInterrupt
else: else:
@ -154,9 +151,9 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
for chunk in response.iter_bytes(chunk_size=1024): for chunk in response.iter_bytes(chunk_size=1024):
signal.signal(signal.SIGINT,signal_handler) signal.signal(signal.SIGINT,signal_handler)
if chunk: if chunk:
size = file.write(chunk) size = file.write(chunk)
downloaded += size downloaded += size
bar.update(size) bar.update(size)
# Optional: Add a check to stop download if needed # Optional: Add a check to stop download if needed
# if downloaded > MAX_DOWNLOAD_SIZE: # if downloaded > MAX_DOWNLOAD_SIZE:
# break # break
@ -172,11 +169,9 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
)) ))
if TELEGRAM_BOT: if TELEGRAM_BOT:
message = f"Download completato\nDimensione: {internet_manager.format_file_size(os.path.getsize(path))}\nDurata: {print_duration_table(path, description=False, return_string=True)}\nTitolo: {os.path.basename(path.replace('.mp4', ''))}" message = f"Download completato\nDimensione: {internet_manager.format_file_size(os.path.getsize(path))}\nDurata: {print_duration_table(path, description=False, return_string=True)}\nTitolo: {os.path.basename(path.replace('.mp4', ''))}"
# Rimuovere i tag di colore usando una regex clean_message = re.sub(r'\[[a-zA-Z]+\]', '', message)
clean_message = re.sub(r'\[[a-zA-Z]+\]', '', message) bot.send_message(clean_message, None)
# Invio a telegram
bot.send_message(clean_message, None)
return path return path
@ -184,16 +179,6 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
console.print("[bold red]Download failed or file is empty.[/bold red]") console.print("[bold red]Download failed or file is empty.[/bold red]")
return None return None
except httpx.HTTPStatusError as http_err:
logging.error(f"HTTP error occurred: {http_err}")
console.print(f"[bold red]HTTP Error: {http_err}[/bold red]")
return None
except httpx.RequestError as req_err:
logging.error(f"Request error: {req_err}")
console.print(f"[bold red]Request Error: {req_err}[/bold red]")
return None
except Exception as e: except Exception as e:
logging.error(f"Unexpected error during download: {e}") logging.error(f"Unexpected error during download: {e}")
console.print(f"[bold red]Unexpected Error: {e}[/bold red]") console.print(f"[bold red]Unexpected Error: {e}[/bold red]")

View File

@ -27,6 +27,7 @@ PORT = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['port'])
USERNAME = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['user']) USERNAME = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['user'])
PASSWORD = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['pass']) PASSWORD = str(config_manager.get_dict('DEFAULT', 'config_qbit_tor')['pass'])
# Config # Config
TQDM_USE_LARGE_BAR = not ("android" in sys.platform or "ios" in sys.platform) TQDM_USE_LARGE_BAR = not ("android" in sys.platform or "ios" in sys.platform)
REQUEST_TIMEOUT = config_manager.get_float('REQUESTS', 'timeout') REQUEST_TIMEOUT = config_manager.get_float('REQUESTS', 'timeout')

View File

@ -110,6 +110,8 @@ def join_video(video_path: str, out_path: str, codec: M3U8_Codec = None):
capture_ffmpeg_real_time(ffmpeg_cmd, "[cyan]Join video") capture_ffmpeg_real_time(ffmpeg_cmd, "[cyan]Join video")
print() print()
return out_path
def join_audios(video_path: str, audio_tracks: List[Dict[str, str]], out_path: str, codec: M3U8_Codec = None): def join_audios(video_path: str, audio_tracks: List[Dict[str, str]], out_path: str, codec: M3U8_Codec = None):
""" """
@ -204,6 +206,8 @@ def join_audios(video_path: str, audio_tracks: List[Dict[str, str]], out_path: s
capture_ffmpeg_real_time(ffmpeg_cmd, "[cyan]Join audio") capture_ffmpeg_real_time(ffmpeg_cmd, "[cyan]Join audio")
print() print()
return out_path
def join_subtitle(video_path: str, subtitles_list: List[Dict[str, str]], out_path: str): def join_subtitle(video_path: str, subtitles_list: List[Dict[str, str]], out_path: str):
""" """
@ -255,4 +259,6 @@ def join_subtitle(video_path: str, subtitles_list: List[Dict[str, str]], out_pat
console.log(f"[purple]FFmpeg [white][[cyan]Join subtitle[white]] ...") console.log(f"[purple]FFmpeg [white][[cyan]Join subtitle[white]] ...")
with suppress_output(): with suppress_output():
capture_ffmpeg_real_time(ffmpeg_cmd, "[cyan]Join subtitle") capture_ffmpeg_real_time(ffmpeg_cmd, "[cyan]Join subtitle")
print() print()
return out_path

View File

@ -22,7 +22,7 @@ TQDM_USE_LARGE_BAR = not ("android" in sys.platform or "ios" in sys.platform)
class M3U8_Ts_Estimator: class M3U8_Ts_Estimator:
def __init__(self, total_segments: int): def __init__(self, total_segments: int, segments_instance=None):
""" """
Initialize the M3U8_Ts_Estimator object. Initialize the M3U8_Ts_Estimator object.
@ -32,6 +32,7 @@ class M3U8_Ts_Estimator:
self.ts_file_sizes = [] self.ts_file_sizes = []
self.now_downloaded_size = 0 self.now_downloaded_size = 0
self.total_segments = total_segments self.total_segments = total_segments
self.segments_instance = segments_instance
self.lock = threading.Lock() self.lock = threading.Lock()
self.speed = {"upload": "N/A", "download": "N/A"} self.speed = {"upload": "N/A", "download": "N/A"}
@ -102,7 +103,6 @@ class M3U8_Ts_Estimator:
return "Error" return "Error"
def update_progress_bar(self, total_downloaded: int, duration: float, progress_counter: tqdm) -> None: def update_progress_bar(self, total_downloaded: int, duration: float, progress_counter: tqdm) -> None:
"""Updates the progress bar with download information."""
try: try:
self.add_ts_file(total_downloaded * self.total_segments, total_downloaded, duration) self.add_ts_file(total_downloaded * self.total_segments, total_downloaded, duration)
@ -120,21 +120,25 @@ class M3U8_Ts_Estimator:
if len(speed_data) >= 2: if len(speed_data) >= 2:
average_internet_speed = speed_data[0] average_internet_speed = speed_data[0]
average_internet_unit = speed_data[1] average_internet_unit = speed_data[1]
else: else:
average_internet_speed = "N/A" average_internet_speed = "N/A"
average_internet_unit = "" average_internet_unit = ""
# Retrieve retry count from segments_instance
retry_count = self.segments_instance.active_retries if self.segments_instance else 0
progress_str = ( progress_str = (
f"{Colors.WHITE}[ {Colors.GREEN}{number_file_downloaded} {Colors.WHITE}< " f"{Colors.WHITE}[ {Colors.GREEN}{number_file_downloaded} {Colors.WHITE}< "
f"{Colors.GREEN}{number_file_total_size} {Colors.RED}{units_file_total_size} " f"{Colors.GREEN}{number_file_total_size} {Colors.RED}{units_file_total_size} "
f"{Colors.WHITE}| {Colors.CYAN}{average_internet_speed} {Colors.RED}{average_internet_unit}" f"{Colors.WHITE}| {Colors.CYAN}{average_internet_speed} {Colors.RED}{average_internet_unit} "
f"{Colors.WHITE}| {Colors.GREEN}CRR {Colors.RED}{retry_count}"
) )
else: else:
# Retrieve retry count from segments_instance
retry_count = self.segments_instance.active_retries if self.segments_instance else 0
progress_str = ( progress_str = (
f"{Colors.WHITE}[ {Colors.GREEN}{number_file_downloaded} {Colors.WHITE}< " f"{Colors.WHITE}[ {Colors.GREEN}{number_file_downloaded} {Colors.WHITE}< "
f"{Colors.GREEN}{number_file_total_size} {Colors.RED}{units_file_total_size}" f"{Colors.GREEN}{number_file_total_size} {Colors.RED}{units_file_total_size} "
f"{Colors.WHITE}| {Colors.GREEN}CRR {Colors.RED}{retry_count}"
) )
progress_counter.set_postfix_str(progress_str) progress_counter.set_postfix_str(progress_str)

View File

@ -0,0 +1,82 @@
# 04.02.25
# Made by: @GiuPic
import json
import time
from typing import Optional
class RequestManager:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, json_file: str = "active_requests.json"):
if not hasattr(self, 'initialized'):
self.json_file = json_file
self.initialized = True
self.on_response_callback = None
def create_request(self, type: str) -> str:
request_data = {
"type": type,
"response": None,
"timestamp": time.time()
}
with open(self.json_file, "w") as f:
json.dump(request_data, f)
return "Ok"
def save_response(self, message_text: str) -> bool:
try:
# Carica il file JSON
with open(self.json_file, "r") as f:
data = json.load(f)
# Controlla se esiste la chiave 'type' e se la risposta è presente
if "type" in data and "response" in data:
data["response"] = message_text # Aggiorna la risposta
with open(self.json_file, "w") as f:
json.dump(data, f, indent=4)
return True
else:
return False
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"⚠️ save_response - errore: {e}")
return False
def get_response(self) -> Optional[str]:
try:
with open(self.json_file, "r") as f:
data = json.load(f)
# Verifica se esiste la chiave "response"
if "response" in data:
response = data["response"] # Ottieni la risposta direttamente
if response is not None and self.on_response_callback:
self.on_response_callback(response)
return response
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"get_response - errore: {e}")
return None
def clear_file(self) -> bool:
try:
with open(self.json_file, "w") as f:
json.dump({}, f)
print(f"File {self.json_file} è stato svuotato con successo.")
return True
except Exception as e:
print(f"⚠️ clear_file - errore: {e}")
return False

View File

@ -1,24 +1,22 @@
# 04.02.25
# Made by: @GiuPic
import json import json
session_data = {} session_data = {}
def set_session(value): def set_session(value):
# salvo script_id in session_data
session_data['script_id'] = value session_data['script_id'] = value
def get_session(): def get_session():
# controllo se script_id è presente in session_data
return session_data.get('script_id', 'unknown') return session_data.get('script_id', 'unknown')
def updateScriptId(screen_id, titolo): def updateScriptId(screen_id, titolo):
# definisco il nome del file json
json_file = "scripts.json" json_file = "scripts.json"
try: try:
# apro il file json
with open(json_file, 'r') as f: with open(json_file, 'r') as f:
scripts_data = json.load(f) scripts_data = json.load(f)
except FileNotFoundError: except FileNotFoundError:
# Se il file non esiste, inizializzo la lista vuota
scripts_data = [] scripts_data = []
# cerco lo script con lo screen_id # cerco lo script con lo screen_id
@ -26,37 +24,33 @@ def updateScriptId(screen_id, titolo):
if script["screen_id"] == screen_id: if script["screen_id"] == screen_id:
# se trovo il match, aggiorno il titolo # se trovo il match, aggiorno il titolo
script["titolo"] = titolo script["titolo"] = titolo
# aggiorno il file json # aggiorno il file json
with open(json_file, 'w') as f: with open(json_file, 'w') as f:
json.dump(scripts_data, f, indent=4) json.dump(scripts_data, f, indent=4)
#print(f"Titolo aggiornato per screen_id {screen_id}")
return return
# se non trovo nessuno script con lo screen_id
print(f"Screen_id {screen_id} non trovato.") print(f"Screen_id {screen_id} non trovato.")
# creo la funzione che elimina lo script con lo screen_id specificato
def deleteScriptId(screen_id): def deleteScriptId(screen_id):
# definisco il nome del file json
json_file = "scripts.json" json_file = "scripts.json"
try: try:
# apro il file json
with open(json_file, 'r') as f: with open(json_file, 'r') as f:
scripts_data = json.load(f) scripts_data = json.load(f)
except FileNotFoundError: except FileNotFoundError:
# Se il file non esiste, inizializzo la lista vuota
scripts_data = [] scripts_data = []
# cerco lo script con lo screen_id
for script in scripts_data: for script in scripts_data:
if script["screen_id"] == screen_id: if script["screen_id"] == screen_id:
# se trovo il match, elimino lo script # se trovo il match, elimino lo script
scripts_data.remove(script) scripts_data.remove(script)
# aggiorno il file json # aggiorno il file json
with open(json_file, 'w') as f: with open(json_file, 'w') as f:
json.dump(scripts_data, f, indent=4) json.dump(scripts_data, f, indent=4)
print(f"Script eliminato per screen_id {screen_id}") print(f"Script eliminato per screen_id {screen_id}")
return return
# se non trovo nessuno script con lo screen_id
print(f"Screen_id {screen_id} non trovato.") print(f"Screen_id {screen_id} non trovato.")

View File

@ -1,13 +1,24 @@
import telebot # 04.02.25
from telebot import types # Made by: @GiuPic
import os
import re
import sys
import time import time
import uuid import uuid
import subprocess
import os, re, sys
import json import json
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from StreamingCommunity.HelpTg.request_manager import RequestManager
import threading import threading
import subprocess
# External libraries
import telebot
# Fix import
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from StreamingCommunity.TelegramHelp.request_manager import RequestManager
# Funzione per caricare variabili da un file .env # Funzione per caricare variabili da un file .env
def load_env(file_path="../../.env"): def load_env(file_path="../../.env"):
@ -21,6 +32,7 @@ def load_env(file_path="../../.env"):
# Carica le variabili # Carica le variabili
load_env() load_env()
class TelegramBot: class TelegramBot:
_instance = None _instance = None
_config_file = "../../bot_config.json" _config_file = "../../bot_config.json"
@ -30,11 +42,15 @@ class TelegramBot:
if cls._instance is None: if cls._instance is None:
# Prova a caricare la configurazione e inizializzare il bot # Prova a caricare la configurazione e inizializzare il bot
if os.path.exists(cls._config_file): if os.path.exists(cls._config_file):
with open(cls._config_file, 'r') as f: with open(cls._config_file, "r") as f:
config = json.load(f) config = json.load(f)
cls._instance = cls.init_bot(config['token'], config['authorized_user_id']) cls._instance = cls.init_bot(
config["token"], config["authorized_user_id"]
)
else: else:
raise Exception("Bot non ancora inizializzato. Chiamare prima init_bot() con token e authorized_user_id") raise Exception(
"Bot non ancora inizializzato. Chiamare prima init_bot() con token e authorized_user_id"
)
return cls._instance return cls._instance
@classmethod @classmethod
@ -42,16 +58,12 @@ class TelegramBot:
if cls._instance is None: if cls._instance is None:
cls._instance = cls(token, authorized_user_id) cls._instance = cls(token, authorized_user_id)
# Salva la configurazione # Salva la configurazione
config = { config = {"token": token, "authorized_user_id": authorized_user_id}
'token': token, with open(cls._config_file, "w") as f:
'authorized_user_id': authorized_user_id
}
with open(cls._config_file, 'w') as f:
json.dump(config, f) json.dump(config, f)
return cls._instance return cls._instance
def __init__(self, token, authorized_user_id): def __init__(self, token, authorized_user_id):
def monitor_scripts(): def monitor_scripts():
while True: while True:
try: try:
@ -68,25 +80,41 @@ class TelegramBot:
for script in scripts_data: for script in scripts_data:
screen_exists = False screen_exists = False
try: try:
existing_screens = subprocess.check_output(["screen", "-list"]).decode('utf-8') existing_screens = subprocess.check_output(
["screen", "-list"]
).decode("utf-8")
if script["screen_id"] in existing_screens: if script["screen_id"] in existing_screens:
screen_exists = True screen_exists = True
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
pass # Se il comando fallisce, significa che non ci sono screen attivi. pass # Se il comando fallisce, significa che non ci sono screen attivi.
if screen_exists: if screen_exists:
if "titolo" not in script and script["status"] == "running" and (current_time - script["start_time"]) > 600: if (
"titolo" not in script
and script["status"] == "running"
and (current_time - script["start_time"]) > 600
):
# Prova a terminare la sessione screen # Prova a terminare la sessione screen
try: try:
subprocess.check_output(["screen", "-S", script["screen_id"], "-X", "quit"]) subprocess.check_output(
print(f"✅ La sessione screen con ID {script['screen_id']} è stata fermata automaticamente.") ["screen", "-S", script["screen_id"], "-X", "quit"]
)
print(
f"✅ La sessione screen con ID {script['screen_id']} è stata fermata automaticamente."
)
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
print(f"⚠️ Impossibile fermare la sessione screen con ID {script['screen_id']}.") print(
print(f"⚠️ Lo script con ID {script['screen_id']} ha superato i 10 minuti e verrà rimosso.") f"⚠️ Impossibile fermare la sessione screen con ID {script['screen_id']}."
)
print(
f"⚠️ Lo script con ID {script['screen_id']} ha superato i 10 minuti e verrà rimosso."
)
else: else:
scripts_data_to_save.append(script) scripts_data_to_save.append(script)
else: else:
print(f"⚠️ La sessione screen con ID {script['screen_id']} non esiste più e verrà rimossa.") print(
f"⚠️ La sessione screen con ID {script['screen_id']} non esiste più e verrà rimossa."
)
# Salva la lista aggiornata, senza gli script scaduti o le screen non esistenti # Salva la lista aggiornata, senza gli script scaduti o le screen non esistenti
with open("../../scripts.json", "w") as f: with open("../../scripts.json", "w") as f:
@ -98,9 +126,10 @@ class TelegramBot:
monitor_thread = threading.Thread(target=monitor_scripts, daemon=True) monitor_thread = threading.Thread(target=monitor_scripts, daemon=True)
monitor_thread.start() monitor_thread.start()
if TelegramBot._instance is not None: if TelegramBot._instance is not None:
raise Exception("Questa classe è un singleton! Usa get_instance() per ottenere l'istanza.") raise Exception(
"Questa classe è un singleton! Usa get_instance() per ottenere l'istanza."
)
self.token = token self.token = token
self.authorized_user_id = authorized_user_id self.authorized_user_id = authorized_user_id
@ -113,67 +142,30 @@ class TelegramBot:
def register_handlers(self): def register_handlers(self):
""" @self.bot.message_handler(commands=['start']) """@self.bot.message_handler(commands=['start'])
def start(message): def start(message):
self.handle_start(message) """ self.handle_start(message)"""
@self.bot.message_handler(commands=['get_id']) @self.bot.message_handler(commands=["get_id"])
def get_id(message): def get_id(message):
self.handle_get_id(message) self.handle_get_id(message)
@self.bot.message_handler(commands=['start']) @self.bot.message_handler(commands=["start"])
def start_script(message): def start_script(message):
self.handle_start_script(message) self.handle_start_script(message)
@self.bot.message_handler(commands=['list']) @self.bot.message_handler(commands=["list"])
def list_scripts(message): def list_scripts(message):
self.handle_list_scripts(message) self.handle_list_scripts(message)
@self.bot.message_handler(commands=['stop']) @self.bot.message_handler(commands=["stop"])
def stop_script(message): def stop_script(message):
self.handle_stop_script(message) self.handle_stop_script(message)
@self.bot.message_handler(commands=['screen']) @self.bot.message_handler(commands=["screen"])
def screen_status(message): def screen_status(message):
self.handle_screen_status(message) self.handle_screen_status(message)
""" @self.bot.message_handler(commands=['replay'])
def send_welcome(message):
# Crea una tastiera personalizzata
markup = types.ReplyKeyboardMarkup(row_width=2)
itembtn1 = types.KeyboardButton('Start')
itembtn2 = types.KeyboardButton('Lista')
markup.add(itembtn1, itembtn2)
# Invia un messaggio con la tastiera
self.bot.send_message(message.chat.id, "Scegli un'opzione:", reply_markup=markup) """
"""@self.bot.message_handler(commands=['inline'])
def send_welcome(message):
# Crea una tastiera inline
markup = types.InlineKeyboardMarkup()
itembtn1 = types.InlineKeyboardButton('Azione 1', callback_data='action1')
itembtn2 = types.InlineKeyboardButton('Azione 2', callback_data='action2')
itembtn3 = types.InlineKeyboardButton('Azione 3', callback_data='action3')
markup.add(itembtn1, itembtn2, itembtn3)
# Invia un messaggio con la tastiera inline
self.bot.send_message(message.chat.id, "Scegli un'opzione:", reply_markup=markup)
# Gestisce le callback delle tastiere inline
@self.bot.callback_query_handler(func=lambda call: True)
def handle_callback(call):
if call.data == 'action1':
self.bot.answer_callback_query(call.id, "Hai scelto Azione 1!")
self.bot.send_message(call.message.chat.id, "Hai eseguito Azione 1!")
elif call.data == 'action2':
self.bot.answer_callback_query(call.id, "Hai scelto Azione 2!")
self.bot.send_message(call.message.chat.id, "Hai eseguito Azione 2!")
elif call.data == 'action3':
self.bot.answer_callback_query(call.id, "Hai scelto Azione 3!")
self.bot.send_message(call.message.chat.id, "Hai eseguito Azione 3!")
"""
@self.bot.message_handler(func=lambda message: True) @self.bot.message_handler(func=lambda message: True)
def handle_all_messages(message): def handle_all_messages(message):
self.handle_response(message) self.handle_response(message)
@ -188,7 +180,11 @@ class TelegramBot:
return return
print(f"Il tuo ID utente è: `{message.from_user.id}`") print(f"Il tuo ID utente è: `{message.from_user.id}`")
self.bot.send_message(message.chat.id, f"Il tuo ID utente è: `{message.from_user.id}`", parse_mode="Markdown") self.bot.send_message(
message.chat.id,
f"Il tuo ID utente è: `{message.from_user.id}`",
parse_mode="Markdown",
)
def handle_start_script(self, message): def handle_start_script(self, message):
if not self.is_authorized(message.from_user.id): if not self.is_authorized(message.from_user.id):
@ -197,10 +193,6 @@ class TelegramBot:
return return
screen_id = str(uuid.uuid4())[:8] screen_id = str(uuid.uuid4())[:8]
#screen_id = '0000'
# Impostare a True per avviare il test_run.py in modalità verbose per il debug
debug_mode = os.getenv("DEBUG") debug_mode = os.getenv("DEBUG")
verbose = debug_mode verbose = debug_mode
@ -210,16 +202,28 @@ class TelegramBot:
# Verifica se lo screen con il nome esiste già # Verifica se lo screen con il nome esiste già
try: try:
subprocess.check_output(["screen", "-list"]) subprocess.check_output(["screen", "-list"])
existing_screens = subprocess.check_output(["screen", "-list"]).decode('utf-8') existing_screens = subprocess.check_output(["screen", "-list"]).decode(
"utf-8"
)
if screen_id in existing_screens: if screen_id in existing_screens:
print(f"⚠️ Lo script con ID {screen_id} è già in esecuzione.") print(f"⚠️ Lo script con ID {screen_id} è già in esecuzione.")
self.bot.send_message(message.chat.id, f"⚠️ Lo script con ID {screen_id} è già in esecuzione.") self.bot.send_message(
message.chat.id,
f"⚠️ Lo script con ID {screen_id} è già in esecuzione.",
)
return return
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
pass # Se il comando fallisce, significa che non ci sono screen attivi. pass # Se il comando fallisce, significa che non ci sono screen attivi.
# Crea la sessione screen e avvia lo script al suo interno # Crea la sessione screen e avvia lo script al suo interno
command = ["screen", "-dmS", screen_id, "python3", "../../test_run.py", screen_id] command = [
"screen",
"-dmS",
screen_id,
"python3",
"../../test_run.py",
screen_id,
]
# Avvia il comando tramite subprocess # Avvia il comando tramite subprocess
subprocess.Popen(command) subprocess.Popen(command)
@ -229,7 +233,7 @@ class TelegramBot:
"screen_id": screen_id, "screen_id": screen_id,
"start_time": time.time(), "start_time": time.time(),
"status": "running", "status": "running",
"user_id": message.from_user.id "user_id": message.from_user.id,
} }
# Salvataggio nel file JSON # Salvataggio nel file JSON
@ -237,7 +241,7 @@ class TelegramBot:
# Carica i dati esistenti o crea una nuova lista # Carica i dati esistenti o crea una nuova lista
try: try:
with open(json_file, 'r') as f: with open(json_file, "r") as f:
scripts_data = json.load(f) scripts_data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError): except (FileNotFoundError, json.JSONDecodeError):
scripts_data = [] scripts_data = []
@ -246,65 +250,61 @@ class TelegramBot:
scripts_data.append(script_info) scripts_data.append(script_info)
# Scrivi il file aggiornato # Scrivi il file aggiornato
with open(json_file, 'w') as f: with open(json_file, "w") as f:
json.dump(scripts_data, f, indent=4) json.dump(scripts_data, f, indent=4)
def handle_list_scripts(self, message): def handle_list_scripts(self, message):
if not self.is_authorized(message.from_user.id): if not self.is_authorized(message.from_user.id):
print(f"❌ Non sei autorizzato.") print(f"❌ Non sei autorizzato.")
self.bot.send_message(message.chat.id, "❌ Non sei autorizzato.") self.bot.send_message(message.chat.id, "❌ Non sei autorizzato.")
return return
try: try:
with open("../../scripts.json", "r") as f: with open("../../scripts.json", "r") as f:
scripts_data = json.load(f) scripts_data = json.load(f)
except (FileNotFoundError, json.JSONDecodeError): except (FileNotFoundError, json.JSONDecodeError):
scripts_data = [] scripts_data = []
if not scripts_data: if not scripts_data:
print(f"⚠️ Nessuno script registrato.") print(f"⚠️ Nessuno script registrato.")
self.bot.send_message(message.chat.id, "⚠️ Nessuno script registrato.") self.bot.send_message(message.chat.id, "⚠️ Nessuno script registrato.")
return return
current_time = time.time() current_time = time.time()
msg = ["🖥️ **Script Registrati:**\n"] msg = ["🖥️ **Script Registrati:**\n"]
for script in scripts_data: for script in scripts_data:
# Calcola la durata # Calcola la durata
duration = current_time - script["start_time"] duration = current_time - script["start_time"]
if "end_time" in script: if "end_time" in script:
duration = script["end_time"] - script["start_time"] duration = script["end_time"] - script["start_time"]
# Formatta la durata # Formatta la durata
hours, rem = divmod(duration, 3600) hours, rem = divmod(duration, 3600)
minutes, seconds = divmod(rem, 60) minutes, seconds = divmod(rem, 60)
duration_str = f"{int(hours)}h {int(minutes)}m {int(seconds)}s" duration_str = f"{int(hours)}h {int(minutes)}m {int(seconds)}s"
# Icona stato # Icona stato
status_icons = { status_icons = {"running": "🟢", "stopped": "🔴", "completed": ""}
"running": "🟢",
"stopped": "🔴",
"completed": ""
}
# Costruisci riga # Costruisci riga
line = ( line = (
f"• ID: `{script['screen_id']}`\n" f"• ID: `{script['screen_id']}`\n"
f"• Stato: {status_icons.get(script['status'], '')}\n" f"• Stato: {status_icons.get(script['status'], '')}\n"
f"• Stop: `/stop {script['screen_id']}`\n" f"• Stop: `/stop {script['screen_id']}`\n"
f"• Screen: `/screen {script['screen_id']}`\n" f"• Screen: `/screen {script['screen_id']}`\n"
f"• Durata: {duration_str}\n" f"• Durata: {duration_str}\n"
f"• Download:\n{script.get('titolo', 'N/A')}\n" f"• Download:\n{script.get('titolo', 'N/A')}\n"
) )
msg.append(line) msg.append(line)
# Formatta la risposta finale # Formatta la risposta finale
final_msg = "\n".join(msg) final_msg = "\n".join(msg)
if len(final_msg) > 4000: if len(final_msg) > 4000:
final_msg = final_msg[:4000] + "\n[...] (messaggio troncato)" final_msg = final_msg[:4000] + "\n[...] (messaggio troncato)"
print(f"{final_msg}") print(f"{final_msg}")
self.bot.send_message(message.chat.id, final_msg, parse_mode="Markdown") self.bot.send_message(message.chat.id, final_msg, parse_mode="Markdown")
def handle_stop_script(self, message): def handle_stop_script(self, message):
if not self.is_authorized(message.from_user.id): if not self.is_authorized(message.from_user.id):
@ -324,7 +324,9 @@ class TelegramBot:
if not running_scripts: if not running_scripts:
print(f"⚠️ Nessuno script attivo da fermare.") print(f"⚠️ Nessuno script attivo da fermare.")
self.bot.send_message(message.chat.id, "⚠️ Nessuno script attivo da fermare.") self.bot.send_message(
message.chat.id, "⚠️ Nessuno script attivo da fermare."
)
return return
msg = "🖥️ **Script Attivi:**\n" msg = "🖥️ **Script Attivi:**\n"
@ -344,12 +346,18 @@ class TelegramBot:
scripts_data = [] scripts_data = []
# Filtra la lista eliminando lo script con l'ID specificato # Filtra la lista eliminando lo script con l'ID specificato
new_scripts_data = [script for script in scripts_data if script["screen_id"] != screen_id] new_scripts_data = [
script for script in scripts_data if script["screen_id"] != screen_id
]
if len(new_scripts_data) == len(scripts_data): if len(new_scripts_data) == len(scripts_data):
# Nessun elemento rimosso, quindi ID non trovato # Nessun elemento rimosso, quindi ID non trovato
print(f"⚠️ Nessuno script attivo con ID `{screen_id}`.") print(f"⚠️ Nessuno script attivo con ID `{screen_id}`.")
self.bot.send_message(message.chat.id, f"⚠️ Nessuno script attivo con ID `{screen_id}`.", parse_mode="Markdown") self.bot.send_message(
message.chat.id,
f"⚠️ Nessuno script attivo con ID `{screen_id}`.",
parse_mode="Markdown",
)
return return
# Terminare la sessione screen # Terminare la sessione screen
@ -357,8 +365,14 @@ class TelegramBot:
subprocess.check_output(["screen", "-S", screen_id, "-X", "quit"]) subprocess.check_output(["screen", "-S", screen_id, "-X", "quit"])
print(f"✅ La sessione screen con ID {screen_id} è stata fermata.") print(f"✅ La sessione screen con ID {screen_id} è stata fermata.")
except subprocess.CalledProcessError: except subprocess.CalledProcessError:
print(f"⚠️ Impossibile fermare la sessione screen con ID `{screen_id}`.") print(
self.bot.send_message(message.chat.id, f"⚠️ Impossibile fermare la sessione screen con ID `{screen_id}`.", parse_mode="Markdown") f"⚠️ Impossibile fermare la sessione screen con ID `{screen_id}`."
)
self.bot.send_message(
message.chat.id,
f"⚠️ Impossibile fermare la sessione screen con ID `{screen_id}`.",
parse_mode="Markdown",
)
return return
# Salva la lista aggiornata senza lo script eliminato # Salva la lista aggiornata senza lo script eliminato
@ -366,22 +380,13 @@ class TelegramBot:
json.dump(new_scripts_data, f, indent=4) json.dump(new_scripts_data, f, indent=4)
print(f"✅ Script `{screen_id}` terminato con successo!") print(f"✅ Script `{screen_id}` terminato con successo!")
self.bot.send_message(message.chat.id, f"✅ Script `{screen_id}` terminato con successo!", parse_mode="Markdown") self.bot.send_message(
message.chat.id,
f"✅ Script `{screen_id}` terminato con successo!",
parse_mode="Markdown",
)
def handle_response(self, message): def handle_response(self, message):
""" if message.text == 'Start':
self.handle_start_script(self, message)
elif message.text == 'Lista':
self.handle_list_scripts(self, message)
elif message.text == 'Azione 3':
self.bot.send_message(message.chat.id, "Hai scelto Azione 3!")
else:
self.bot.send_message(message.chat.id, "Comando non riconosciuto.")
if not self.is_authorized(message.from_user.id):
self.bot.reply_to(message, "❌ Non sei autorizzato.")
return """
text = message.text text = message.text
if self.request_manager.save_response(text): if self.request_manager.save_response(text):
print(f"📥 Risposta salvata correttamente per il tipo {text}") print(f"📥 Risposta salvata correttamente per il tipo {text}")
@ -393,7 +398,9 @@ class TelegramBot:
command_parts = message.text.split() command_parts = message.text.split()
if len(command_parts) < 2: if len(command_parts) < 2:
print(f"⚠️ ID mancante nel comando. Usa: /screen <ID>") print(f"⚠️ ID mancante nel comando. Usa: /screen <ID>")
self.bot.send_message(message.chat.id, "⚠️ ID mancante nel comando. Usa: /screen <ID>") self.bot.send_message(
message.chat.id, "⚠️ ID mancante nel comando. Usa: /screen <ID>"
)
return return
screen_id = command_parts[1] screen_id = command_parts[1]
@ -401,35 +408,55 @@ class TelegramBot:
try: try:
# Cattura l'output della screen # Cattura l'output della screen
subprocess.run(["screen", "-X", "-S", screen_id, "hardcopy", "-h", temp_file], check=True) subprocess.run(
["screen", "-X", "-S", screen_id, "hardcopy", "-h", temp_file],
check=True,
)
except subprocess.CalledProcessError as e: except subprocess.CalledProcessError as e:
print(f"❌ Errore durante la cattura dell'output della screen: {e}") print(f"❌ Errore durante la cattura dell'output della screen: {e}")
self.bot.send_message(message.chat.id, f"❌ Errore durante la cattura dell'output della screen: {e}") self.bot.send_message(
message.chat.id,
f"❌ Errore durante la cattura dell'output della screen: {e}",
)
return return
if not os.path.exists(temp_file): if not os.path.exists(temp_file):
print(f"❌ Impossibile catturare l'output della screen.") print(f"❌ Impossibile catturare l'output della screen.")
self.bot.send_message(message.chat.id, f"❌ Impossibile catturare l'output della screen.") self.bot.send_message(
message.chat.id, f"❌ Impossibile catturare l'output della screen."
)
return return
try: try:
# Leggi il file con la codifica corretta # Leggi il file con la codifica corretta
with open(temp_file, 'r', encoding='latin-1') as file: with open(temp_file, "r", encoding="latin-1") as file:
screen_output = file.read() screen_output = file.read()
# Pulisci l'output # Pulisci l'output
cleaned_output = re.sub(r'[\x00-\x1F\x7F]', '', screen_output) # Rimuovi caratteri di controllo cleaned_output = re.sub(
cleaned_output = cleaned_output.replace('\n\n', '\n') # Rimuovi newline multipli r"[\x00-\x1F\x7F]", "", screen_output
) # Rimuovi caratteri di controllo
cleaned_output = cleaned_output.replace(
"\n\n", "\n"
) # Rimuovi newline multipli
# Estrarre tutte le parti da "Download:" fino a "Video" o "Subtitle", senza includerli # Estrarre tutte le parti da "Download:" fino a "Video" o "Subtitle", senza includerli
download_matches = re.findall(r"Download: (.*?)(?:Video|Subtitle)", cleaned_output) download_matches = re.findall(
r"Download: (.*?)(?:Video|Subtitle)", cleaned_output
)
if download_matches: if download_matches:
# Serie TV e Film StreamingCommunity # Serie TV e Film StreamingCommunity
proc_matches = re.findall(r"Proc: ([\d\.]+%)", cleaned_output) proc_matches = re.findall(r"Proc: ([\d\.]+%)", cleaned_output)
# Creare una stringa unica con tutti i risultati # Creare una stringa unica con tutti i risultati
result_string = "\n".join([f"Download: {download_matches[i].strip()}\nDownload al {proc_matches[i]}" for i in range(len(download_matches)) if i < len(proc_matches)]) result_string = "\n".join(
[
f"Download: {download_matches[i].strip()}\nDownload al {proc_matches[i]}"
for i in range(len(download_matches))
if i < len(proc_matches)
]
)
if result_string != "": if result_string != "":
cleaned_output = result_string cleaned_output = result_string
@ -461,11 +488,18 @@ class TelegramBot:
# Invia l'output pulito # Invia l'output pulito
print(f"📄 Output della screen {screen_id}:\n{cleaned_output}") print(f"📄 Output della screen {screen_id}:\n{cleaned_output}")
self._send_long_message(message.chat.id, f"📄 Output della screen {screen_id}:\n{cleaned_output}") self._send_long_message(
message.chat.id, f"📄 Output della screen {screen_id}:\n{cleaned_output}"
)
except Exception as e: except Exception as e:
print(f"❌ Errore durante la lettura o l'invio dell'output della screen: {e}") print(
self.bot.send_message(message.chat.id, f"❌ Errore durante la lettura o l'invio dell'output della screen: {e}") f"❌ Errore durante la lettura o l'invio dell'output della screen: {e}"
)
self.bot.send_message(
message.chat.id,
f"❌ Errore durante la lettura o l'invio dell'output della screen: {e}",
)
# Cancella il file temporaneo # Cancella il file temporaneo
os.remove(temp_file) os.remove(temp_file)
@ -486,7 +520,7 @@ class TelegramBot:
"""Suddivide e invia un messaggio troppo lungo in più parti.""" """Suddivide e invia un messaggio troppo lungo in più parti."""
for i in range(0, len(text), chunk_size): for i in range(0, len(text), chunk_size):
print(f"{text[i:i+chunk_size]}") print(f"{text[i:i+chunk_size]}")
self.bot.send_message(chat_id, text[i:i+chunk_size]) self.bot.send_message(chat_id, text[i : i + chunk_size])
def ask(self, type, prompt_message, choices, timeout=60): def ask(self, type, prompt_message, choices, timeout=60):
self.request_manager.create_request(type) self.request_manager.create_request(type)
@ -518,30 +552,10 @@ class TelegramBot:
def run(self): def run(self):
print("🚀 Avvio del bot...") print("🚀 Avvio del bot...")
# svuoto il file ../../scripts.json
with open("../../scripts.json", "w") as f: with open("../../scripts.json", "w") as f:
json.dump([], f) json.dump([], f)
self.bot.infinity_polling() self.bot.infinity_polling()
def get_bot_instance(): def get_bot_instance():
return TelegramBot.get_instance() return TelegramBot.get_instance()
# Esempio di utilizzo
if __name__ == "__main__":
# Usa le variabili
token = os.getenv("TOKEN_TELEGRAM")
authorized_user_id = os.getenv("AUTHORIZED_USER_ID")
TOKEN = token # Inserisci il token del tuo bot Telegram sul file .env
AUTHORIZED_USER_ID = int(authorized_user_id) # Inserisci il tuo ID utente Telegram sul file .env
# Inizializza il bot
bot = TelegramBot.init_bot(TOKEN, AUTHORIZED_USER_ID)
bot.run()
"""
start - Avvia lo script
list - Lista script attivi
get - Mostra ID utente Telegram
"""

View File

@ -25,8 +25,7 @@ def update():
""" """
Check for updates on GitHub and display relevant information. Check for updates on GitHub and display relevant information.
""" """
console.print("\n[cyan]→ [green]Checking GitHub version ...")
console.print("[green]Checking GitHub version [white]...")
# Make the GitHub API requests and handle potential errors # Make the GitHub API requests and handle potential errors
try: try:
@ -59,7 +58,7 @@ def update():
if str(__version__).replace('v', '') != str(last_version).replace('v', '') : if str(__version__).replace('v', '') != str(last_version).replace('v', '') :
console.print(f"[red]New version available: [yellow]{last_version} \n") console.print(f"[red]New version available: [yellow]{last_version} \n")
else: else:
console.print(f" [yellow]Everything is up to date \n") console.print(f" [red]Everything is up to date \n")
console.print(f"[red]{__title__} has been downloaded [yellow]{total_download_count} [red]times, but only [yellow]{percentual_stars}% [red]of users have starred it.\n\ console.print(f"[red]{__title__} has been downloaded [yellow]{total_download_count} [red]times, but only [yellow]{percentual_stars}% [red]of users have starred it.\n\
[cyan]Help the repository grow today by leaving a [yellow]star [cyan]and [yellow]sharing [cyan]it with others online!") [cyan]Help the repository grow today by leaving a [yellow]star [cyan]and [yellow]sharing [cyan]it with others online!")

View File

@ -1,5 +1,5 @@
__title__ = 'StreamingCommunity' __title__ = 'StreamingCommunity'
__version__ = '2.5.0' __version__ = '2.5.0'
__author__ = 'Lovi-0' __author__ = 'Abc-dc'
__description__ = 'A command-line program to download film' __description__ = 'A command-line program to download film'
__copyright__ = 'Copyright 2024' __copyright__ = 'Copyright 2024'

View File

@ -34,7 +34,7 @@ class ConfigManager:
else: else:
logging.info("Configuration file does not exist. Downloading...") logging.info("Configuration file does not exist. Downloading...")
self.download_requirements( self.download_requirements(
'https://raw.githubusercontent.com/Lovi-0/StreamingCommunity/refs/heads/main/config.json', 'https://raw.githubusercontent.com/Abc-dc/StreamingCommunity/refs/heads/main/config.json',
self.file_path self.file_path
) )

View File

@ -7,58 +7,30 @@ import platform
from StreamingCommunity.Util.console import console from StreamingCommunity.Util.console import console
from StreamingCommunity.Util._jsonConfig import config_manager from StreamingCommunity.Util._jsonConfig import config_manager
# Variable # Variable
CLEAN = config_manager.get_bool('DEFAULT', 'clean_console') CLEAN = config_manager.get_bool('DEFAULT', 'clean_console')
SHOW = config_manager.get_bool('DEFAULT', 'show_message') SHOW = config_manager.get_bool('DEFAULT', 'show_message')
def create_italian_flag_colored_text(text: str) -> str:
"""Create text divided into three sections with Italian flag colors, splitting each line at two spaces."""
# Split the text into lines
lines = text.splitlines()
colored_lines = []
for line in lines:
# Split each line into parts using two spaces as a delimiter
parts = line.split(" ")
# Ensure there are exactly 3 parts (add empty strings if necessary)
parts += [''] * (4 - len(parts))
# Apply flag colors to the parts
green_part = f"[green]{parts[0]}[/]"
white_part = f"[white]{parts[1]}[/]"
red_part = f"[red]{parts[2]}[/]"
# Reassemble the colored line
colored_line = green_part + white_part + red_part
colored_lines.append(colored_line)
# Join all colored lines back into a single string
return "\n".join(colored_lines)
def start_message(): def start_message():
"""Display a stylized start message in the console.""" """Display a stylized start message in the console."""
msg = r''' msg = r'''
__ __ _ _____ __ _
/ //_/(_)________ ____ _ __ / ___// /_________ ____ _____ ___ (_)___ ____ _
/ ,< / / ___/ __ \/ __ \ | |/_/ \__ \/ __/ ___/ _ \/ __ `/ __ `__ \/ / __ \/ __ `/
/ /| |/ / / / /_/ / / / / _> < ___/ / /_/ / / __/ /_/ / / / / / / / / / / /_/ /
/_/ |_/_/_/ \____/_/ /_/ /_/|_| /____/\__/_/ \___/\__,_/_/ /_/ /_/_/_/ /_/\__, /
/____/
'''.rstrip() '''.rstrip()
colored_msg = create_italian_flag_colored_text(msg)
if CLEAN: if CLEAN:
os.system("cls" if platform.system() == 'Windows' else "clear") os.system("cls" if platform.system() == 'Windows' else "clear")
if SHOW: if SHOW:
console.print(colored_msg) console.print(f"[purple]{msg}")
# Print a decorative separator line using asterisks # Print a decorative separator line using asterisks
separator = "_" * (console.width - 2) # Ridotto di 2 per il padding separator = "_" * (console.width - 2) # Ridotto di 2 per il padding
console.print(f"[yellow]{separator}[/yellow]\n") console.print(f"[cyan]{separator}[/cyan]\n")

View File

@ -411,7 +411,6 @@ class OsSummary:
def get_system_summary(self): def get_system_summary(self):
self.check_python_version() self.check_python_version()
InternManager().check_internet() InternManager().check_internet()
console.print("[bold blue]System Summary[/bold blue][white]:")
# Python info # Python info
python_version = sys.version.split()[0] python_version = sys.version.split()[0]
@ -477,7 +476,7 @@ class OsSummary:
if not os.path.exists(requirements_file): if not os.path.exists(requirements_file):
self.download_requirements( self.download_requirements(
'https://raw.githubusercontent.com/Lovi-0/StreamingCommunity/refs/heads/main/requirements.txt', 'https://raw.githubusercontent.com/Abc-dc/StreamingCommunity/refs/heads/main/requirements.txt',
requirements_file requirements_file
) )
@ -492,7 +491,7 @@ class OsSummary:
else: else:
logging.info(f"Library: {installed_version}") logging.info(f"Library: {installed_version}")
console.print(f"[cyan]Libraries[white]: [bold red]{', '.join([self.get_library_version(lib) for lib in optional_libraries])}[/bold red]\n") #console.print(f"[cyan]Libraries[white]: [bold red]{', '.join([self.get_library_version(lib) for lib in optional_libraries])}[/bold red]\n")
logging.info(f"Libraries: {', '.join([self.get_library_version(lib) for lib in optional_libraries])}") logging.info(f"Libraries: {', '.join([self.get_library_version(lib) for lib in optional_libraries])}")

View File

@ -19,7 +19,7 @@ from .message import start_message
from .call_stack import get_call_stack from .call_stack import get_call_stack
# Telegram bot instance # Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
from StreamingCommunity.Util._jsonConfig import config_manager from StreamingCommunity.Util._jsonConfig import config_manager
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot') TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')

View File

@ -20,13 +20,16 @@ from StreamingCommunity.Upload.update import update as git_update
from StreamingCommunity.Util.os import os_summary from StreamingCommunity.Util.os import os_summary
from StreamingCommunity.Util.logger import Logger from StreamingCommunity.Util.logger import Logger
# Telegram bot instance
from StreamingCommunity.HelpTg.telegram_bot import get_bot_instance # Telegram util
from StreamingCommunity.TelegramHelp.session import get_session, deleteScriptId
from StreamingCommunity.TelegramHelp.telegram_bot import get_bot_instance
# Config # Config
CLOSE_CONSOLE = config_manager.get_bool('DEFAULT', 'not_close') CLOSE_CONSOLE = config_manager.get_bool('DEFAULT', 'not_close')
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot') TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
from StreamingCommunity.HelpTg.session import get_session, deleteScriptId
def run_function(func: Callable[..., None], close_console: bool = False) -> None: def run_function(func: Callable[..., None], close_console: bool = False) -> None:
@ -136,11 +139,13 @@ def initialize():
except: except:
console.log("[red]Error with loading github.") console.log("[red]Error with loading github.")
def restart_script(): def restart_script():
"""Riavvia lo script con gli stessi argomenti della riga di comando.""" """Riavvia lo script con gli stessi argomenti della riga di comando."""
print("\n🔄 Riavvio dello script...\n") print("\n🔄 Riavvio dello script...\n")
python = sys.executable python = sys.executable
os.execv(python, [python] + sys.argv) # Riavvia lo stesso script con gli stessi argomenti os.execv(python, [python] + sys.argv)
def force_exit(): def force_exit():
"""Forza la chiusura dello script in qualsiasi contesto.""" """Forza la chiusura dello script in qualsiasi contesto."""
@ -160,23 +165,24 @@ def force_exit():
print("⚡ Arresto del loop asyncio...") print("⚡ Arresto del loop asyncio...")
loop.stop() loop.stop()
except RuntimeError: except RuntimeError:
pass # Se non c'è un loop asyncio attivo, ignora l'errore pass
# 3⃣ Esce con sys.exit(), se fallisce usa os._exit() # 3⃣ Esce con sys.exit(), se fallisce usa os._exit()
try: try:
print("✅ Uscita con sys.exit(0)") print("✅ Uscita con sys.exit(0)")
sys.exit(0) sys.exit(0)
except SystemExit: except SystemExit:
pass # Se viene intercettato da un try/except, ignora pass
print("🚨 Uscita forzata con os._exit(0)") print("🚨 Uscita forzata con os._exit(0)")
os._exit(0) # Se sys.exit() non funziona, esce forzatamente os._exit(0)
def main(script_id): def main(script_id):
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot = get_bot_instance() bot = get_bot_instance()
bot.send_message(f"🏁 Avviato script {script_id}", None) bot.send_message(f"🏁 Avviato script {script_id}", None)
start = time.time() start = time.time()
@ -291,41 +297,36 @@ def main(script_id):
if TELEGRAM_BOT: if TELEGRAM_BOT:
# Mappa delle emoji per i colori # Mappa delle emoji per i colori
emoji_map = { emoji_map = {
"yellow": "🟡", # Giallo "yellow": "🟡", # Giallo
"red": "🔴", # Rosso "red": "🔴", # Rosso
"blue": "🔵", # Blu "blue": "🔵", # Blu
"green": "🟢" # Verde "green": "🟢" # Verde
} }
# Display the category legend in a single line # Display the category legend in a single line
category_legend_str = "Categorie: \n" + " | ".join([ category_legend_str = "Categorie: \n" + " | ".join([
f"{emoji_map.get(color, '')} {category.capitalize()}" f"{emoji_map.get(color, '')} {category.capitalize()}"
for category, color in color_map.items() for category, color in color_map.items()
]) ])
# Costruisci il messaggio con le emoji al posto dei colori # Costruisci il messaggio con le emoji al posto dei colori
prompt_message = "Inserisci il sito:\n" + "\n".join( prompt_message = "Inserisci il sito:\n" + "\n".join(
[f"{key}: {emoji_map[color_map[label[1]]]} {label[0]}" for key, label in choice_labels.items()] [f"{key}: {emoji_map[color_map[label[1]]]} {label[0]}" for key, label in choice_labels.items()]
) )
console.print(f"\n{prompt_message}") console.print(f"\n{prompt_message}")
# Chiedi la scelta all'utente con il bot Telegram # Chiedi la scelta all'utente con il bot Telegram
category = bot.ask( category = bot.ask(
"select_provider", "select_provider",
f"{category_legend_str}\n\n{prompt_message}", f"{category_legend_str}\n\n{prompt_message}",
None # Passiamo la lista delle chiavi come scelte None # Passiamo la lista delle chiavi come scelte
) )
else: else:
category = msg.ask(prompt_message, choices=list(choice_labels.keys()), default="0", show_choices=False, show_default=False)
#console.print(f"\n{prompt_message}")
# Ask the user for input
category = msg.ask(prompt_message, choices=list(choice_labels.keys()), default="0", show_choices=False, show_default=False)
# Run the corresponding function based on user input # Run the corresponding function based on user input
if category in input_to_function: if category in input_to_function:
@ -338,18 +339,14 @@ def main(script_id):
console.print("[red]Invalid category.") console.print("[red]Invalid category.")
if CLOSE_CONSOLE: if CLOSE_CONSOLE:
restart_script() # Riavvia lo script invece di uscire restart_script() # Riavvia lo script invece di uscire
# Riavvia lo script
# Chiude il processo attuale e avvia una nuova istanza dello script
""" subprocess.Popen([sys.executable] + sys.argv)
sys.exit() """
else: else:
force_exit() # Usa la funzione per chiudere sempre force_exit() # Usa la funzione per chiudere sempre
if TELEGRAM_BOT: if TELEGRAM_BOT:
bot.send_message(f"Chiusura in corso", None) bot.send_message(f"Chiusura in corso", None)
# Delete script_id
script_id = get_session() # Delete script_id
if script_id != "unknown": script_id = get_session()
deleteScriptId(script_id) if script_id != "unknown":
deleteScriptId(script_id)

View File

@ -20,6 +20,6 @@ from StreamingCommunity.Lib.Downloader import HLS_Downloader
start_message() start_message()
logger = Logger() logger = Logger()
print("Return: ", HLS_Downloader( print("Return: ", HLS_Downloader(
output_filename="test.mp4", output_path="test.mp4",
m3u8_playlist="https://acdn.ak-stream-videoplatform.sky.it/hls/2024/11/21/968275/master.m3u8" m3u8_url="https://acdn.ak-stream-videoplatform.sky.it/hls/2024/11/21/968275/master.m3u8"
).start()) ).start())

View File

@ -0,0 +1,29 @@
# 05.02.25
# Fix import
import sys
import os
src_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..'))
sys.path.append(src_path)
from StreamingCommunity.Util.ffmpeg_installer import FFMPEGDownloader
def test_ffmpeg_downloader():
# Create an instance of the downloader
downloader = FFMPEGDownloader()
# Check if the download method works and fetches the executables
ffmpeg, ffprobe, ffplay = downloader.download()
# Output the destination paths
print(f"FFmpeg path: {ffmpeg}")
print(f"FFprobe path: {ffprobe}")
print(f"FFplay path: {ffplay}")
if __name__ == "__main__":
test_ffmpeg_downloader()

View File

@ -3,15 +3,15 @@
"debug": false, "debug": false,
"log_file": "app.log", "log_file": "app.log",
"log_to_file": false, "log_to_file": false,
"show_message": false, "show_message": true,
"clean_console": true, "clean_console": true,
"root_path": "/home/giuseppepiccolo/Develop/docker/jellyfin/media/", "root_path": "Video",
"movie_folder_name": "Movie", "movie_folder_name": "Movie",
"serie_folder_name": "Serie", "serie_folder_name": "Serie",
"anime_folder_name": "Anime", "anime_folder_name": "Anime",
"map_episode_name": "%(tv_name)_S%(season)E%(episode)_%(episode_name)", "map_episode_name": "S%(season)E%(episode)_%(episode_name)",
"config_qbit_tor": { "config_qbit_tor": {
"host": "192.168.5.172", "host": "192.168.5.99",
"port": "8080", "port": "8080",
"user": "admin", "user": "admin",
"pass": "adminadmin" "pass": "adminadmin"
@ -19,10 +19,10 @@
"add_siteName": false, "add_siteName": false,
"disable_searchDomain": false, "disable_searchDomain": false,
"not_close": false, "not_close": false,
"telegram_bot": true "telegram_bot": false
}, },
"REQUESTS": { "REQUESTS": {
"timeout": 30, "timeout": 20,
"max_retry": 8, "max_retry": 8,
"proxy_start_min": 0.1, "proxy_start_min": 0.1,
"proxy_start_max": 0.5 "proxy_start_max": 0.5
@ -35,7 +35,7 @@
"specific_list_audio": [ "specific_list_audio": [
"ita" "ita"
], ],
"merge_subs": false, "merge_subs": true,
"specific_list_subtitles": [ "specific_list_subtitles": [
"eng", "eng",
"spa" "spa"
@ -79,7 +79,7 @@
"domain": "so" "domain": "so"
}, },
"cb01new": { "cb01new": {
"domain": "mobi" "domain": "media"
}, },
"1337xx": { "1337xx": {
"domain": "to" "domain": "to"

View File

@ -11,6 +11,6 @@ pycryptodomex
googlesearch-python googlesearch-python
fake-useragent fake-useragent
qbittorrent-api qbittorrent-api
python-qbittorrent python-qbittorrent
pyTelegramBotAPI Pillow
Pillow pyTelegramBotAPI

View File

@ -2,14 +2,20 @@
import sys import sys
from StreamingCommunity.run import main from StreamingCommunity.run import main
from StreamingCommunity.HelpTg.request_manager import RequestManager from StreamingCommunity.Util._jsonConfig import config_manager
from StreamingCommunity.HelpTg.session import set_session from StreamingCommunity.TelegramHelp.request_manager import RequestManager
from StreamingCommunity.TelegramHelp.session import set_session
# Svuoto il file # Svuoto il file
request_manager = RequestManager() TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
request_manager.clear_file()
script_id = sys.argv[1] if len(sys.argv) > 1 else "unknown"
set_session(script_id) if TELEGRAM_BOT:
request_manager = RequestManager()
request_manager.clear_file()
script_id = sys.argv[1] if len(sys.argv) > 1 else "unknown"
main(script_id) set_session(script_id)
main(script_id)
else:
main(0)