code workflow - panuozzo77/StreamingCommunity GitHub Wiki
This document explains the workflow of the StreamingCommunity application, focusing on what happens when a user starts the program and how the different components interact.
The main entry point for the StreamingCommunity application is the main()
function in the run.py
file. This function orchestrates the entire workflow of the application, from initialization to content selection and downloading.
When a user starts the StreamingCommunity application, the following sequence of events occurs:
- Initialization: The application initializes, displays welcome messages, and checks system information
-
Configuration Loading: Configuration settings are loaded from the
config.json
file - Module Loading: Available site modules are dynamically loaded
- Command Line Parsing: Command line arguments are parsed to override configuration settings
- Site Selection: The user selects a streaming site or chooses global search
- Content Search: The user searches for content on the selected site(s)
- Content Selection: The user selects specific content to download
- Download Process: The selected content is downloaded using the appropriate method
- Post-Processing: Downloaded content is processed according to configuration settings
The initialization process is handled by the initialize()
function, which:
- Displays the welcome message via
start_message()
- Retrieves system information via
os_summary.get_system_summary()
- Adjusts terminal size for Windows 7 systems
- Checks Python version compatibility
- Displays trending content from TMDB if enabled
- Attempts to update the application from GitHub
def initialize():
# Get start message
start_message()
# Get system info
os_summary.get_system_summary()
# Set terminal size for win 7
if platform.system() == "Windows" and "7" in platform.version():
os.system('mode 120, 40')
# Check python version
if sys.version_info < (3, 7):
console.log("[red]Install python version > 3.7.16")
sys.exit(0)
# Trending tmbd
if SHOW_TRENDING:
print()
tmdb.display_trending_films()
tmdb.display_trending_tv_shows()
# Attempting GitHub update
try:
git_update()
except:
console.log("[red]Error with loading github.")
The application dynamically loads all available site modules using the load_search_functions()
function:
- It identifies all site modules in the
StreamingCommunity/Api/Site
directory - It imports each module and retrieves its search function
- It organizes modules by their index value and categorizes them by type (anime, film, series, etc.)
- It excludes deprecated modules and those incompatible with Telegram bot mode if enabled
def load_search_functions():
modules = []
loaded_functions = {}
# List of sites to exclude if TELEGRAM_BOT is active
excluded_sites = {"cb01new", "ddlstreamitaly", "guardaserie", "ilcorsaronero", "mostraguarda"} if TELEGRAM_BOT else set()
# Find api home directory
if getattr(sys, 'frozen', False): # PyInstaller mode
base_path = os.path.join(sys._MEIPASS, "StreamingCommunity")
else:
base_path = os.path.dirname(__file__)
api_dir = os.path.join(base_path, 'Api', 'Site')
init_files = glob.glob(os.path.join(api_dir, '*', '__init__.py'))
# Retrieve modules and their indices
for init_file in init_files:
# Get folder name as module name
module_name = os.path.basename(os.path.dirname(init_file))
# Skip if module is in the exclusion list
if module_name in excluded_sites:
continue
# ... (module loading logic)
# Sort modules by 'indice'
modules.sort(key=lambda x: x[1])
# Load search functions in the sorted order
for module_name, _, use_for in modules:
# ... (function loading logic)
return loaded_functions
The application uses argparse
to parse command line arguments, which can override configuration settings:
- It creates an argument parser with descriptions for each option
- It adds arguments for configuration parameters, site selection, and search terms
- It parses the provided arguments
- It applies any configuration updates based on the arguments
# Create argument parser
parser = argparse.ArgumentParser(
description='Script to download movies and series from the internet. Use these commands to configure the script and control its behavior.'
)
# Add arguments for the main configuration parameters
parser.add_argument(
'--add_siteName', type=bool, help='Enable or disable adding the site name to the file name (e.g., true/false).'
)
# ... (more arguments)
# Parse command-line arguments
args = parser.parse_args()
# Map command-line arguments to the config values
config_updates = {}
if args.add_siteName is not None:
config_updates['DEFAULT.add_siteName'] = args.add_siteName
# ... (more config updates)
# Apply the updates to the config file
for key, value in config_updates.items():
section, option = key.split('.')
config_manager.set_key(section, option, value)
config_manager.save_config()
The application presents the user with a list of available streaming sites:
- It displays a menu of available sites, color-coded by category
- The user selects a site by number
- The corresponding search function is called
- If global search is selected, the
global_search()
function is called instead
# Mapping user input to functions
input_to_function = {str(i): func for i, (alias, (func, _)) in enumerate(search_functions.items())}
# Create dynamic prompt message and choices
choice_labels = {str(i): (alias.split("_")[0].capitalize(), use_for) for i, (alias, (_, use_for)) in enumerate(search_functions.items())}
# Display the category legend in a single line
legend_text = " | ".join([f"[{color}]{category.capitalize()}[/{color}]" for category, color in color_map.items()])
console.print(f"\n[bold green]Category Legend:[/bold green] {legend_text}")
# Construct the prompt message with color-coded site names
prompt_message = "[green]Insert category [white](" + ", ".join(
[f"{key}: [{color_map.get(label[1], 'white')}]{label[0]}[/{color_map.get(label[1], 'white')}]" for key, label in choice_labels.items()]
) + "[white])"
# Get user selection
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
if category in input_to_function:
run_function(input_to_function[category], search_terms=search_terms)
Each site module implements a search()
function that:
- Prompts the user for search terms (if not provided via command line)
- Queries the streaming site for matching content
- Displays the search results
- Allows the user to select content for viewing or downloading
The specific implementation varies by site, but the general pattern is:
def search(search_terms=None):
# Get search terms from user if not provided
if not search_terms:
search_terms = get_search_input()
# Query the site API or scrape the site for results
results = query_site(search_terms)
# Display results to user
display_results(results)
# Get user selection
selection = get_user_selection(results)
# Process the selected content
process_selection(selection)
Once content is selected, it is processed according to its type:
- Movies: Typically downloaded directly
- TV Series: The user selects season and episode(s) to download
- Anime: Similar to TV series, with season and episode selection
The download process depends on the content type and source:
-
HLS (M3U8) Content: Processed by the
HLS_Downloader
class -
Direct MP4 Files: Processed by the
MP4_downloader
class -
Torrent Content: Processed by the
TOR_downloader
class
After download, content is processed according to configuration settings:
- Audio tracks are merged if enabled
- Subtitles are merged if enabled
- Temporary files are cleaned up if enabled
- The final file is moved to the configured output directory
The program terminates based on the not_close
configuration:
- If
not_close
istrue
, the program loops back to the site selection step - If
not_close
isfalse
, the program exits
def run_function(func: Callable[..., None], close_console: bool = False, search_terms: str = None) -> None:
if close_console:
while 1:
func(search_terms)
else:
func(search_terms)
The global search feature follows a slightly different workflow:
- The user selects global search mode
- The user is presented with search options:
- Search all sites
- Search by category
- Select specific sites
- The user enters search terms
- The application searches across the selected sites
- Results are consolidated and displayed
- The user selects content to download
- The appropriate site-specific function handles the download
When Telegram bot integration is enabled, the workflow changes:
- The bot receives commands from the user via Telegram
- Commands are processed and mapped to application functions
- Results and prompts are sent back to the user via Telegram
- Downloads run in separate screen sessions for parallel operation
The application includes several error handling mechanisms:
-
Graceful Termination: The
force_exit()
function ensures clean shutdown -
Restart Capability: The
restart_script()
function allows restarting the application - Exception Handling: Try-except blocks catch and handle errors throughout the code
The StreamingCommunity application follows a modular, user-driven workflow that:
- Initializes the environment
- Loads available site modules
- Presents options to the user
- Processes user selections
- Downloads and processes content
- Terminates or loops based on configuration
This design allows for flexibility in adding new sites and features while maintaining a consistent user experience.