Dynamic import.

This commit is contained in:
Lovi 2024-06-14 16:58:21 +02:00
parent e202eab5c7
commit b27abc6fc8
6 changed files with 98 additions and 49 deletions

View File

@ -5,14 +5,13 @@ from Src.Util.console import console, msg
# Logic class # Logic class
from .site import ( from .site import title_search, get_select_title
title_search,
get_select_title,
)
from .film import download_film from .film import download_film
# Variable
indice = 2
def search(): def search():
""" """
Main function of the application for film and series. Main function of the application for film and series.

View File

@ -9,6 +9,10 @@ from .site import title_search, get_select_title
from .anime import donwload_film, donwload_series from .anime import donwload_film, donwload_series
# Variable
indice = 1
def search(): def search():
# Make request to site to get content that corrsisponde to that string # Make request to site to get content that corrsisponde to that string

View File

@ -13,6 +13,10 @@ from .site import title_search, get_select_title
from .series import download_thread from .series import download_thread
# Variable
indice = 3
def search(): def search():
""" """
Main function of the application for film and series. Main function of the application for film and series.

View File

@ -9,6 +9,10 @@ from .site import title_search, get_select_title
from .series import download_series from .series import download_series
# Variable
indice = 4
def search(): def search():
""" """
Main function of the application for film and series. Main function of the application for film and series.

View File

@ -15,16 +15,19 @@ from .film import download_film
from .series import download_series from .series import download_series
# Variable
indice = 0
def search(): def search():
""" """
Main function of the application for film and series. Main function of the application for film and series.
""" """
# Get site domain and version
site_version, domain = get_version_and_domain()
# Make request to site to get content that corrsisponde to that string # Make request to site to get content that corrsisponde to that string
string_to_search = msg.ask("\n[purple]Insert word to search in all site").strip() string_to_search = msg.ask("\n[purple]Insert word to search in all site").strip()
# Get site domain and version and get result of the search
site_version, domain = get_version_and_domain()
len_database = title_search(string_to_search, domain) len_database = title_search(string_to_search, domain)
if len_database > 0: if len_database > 0:

117
run.py
View File

@ -1,9 +1,11 @@
# 10.12.23 # 10.12.23
import sys
import os import os
import sys
import glob
import platform import platform
import argparse import argparse
import importlib
from typing import Callable from typing import Callable
@ -17,18 +19,11 @@ from Src.Util.os import get_system_summary
from Src.Util.logger import Logger from Src.Util.logger import Logger
# Internal api
from Src.Api.Streamingcommunity import search as streamingcommunity_film_serie
from Src.Api.Animeunity import search as streamingcommunity_anime
from Src.Api.Altadefinizione import search as altadefinizione_film
from Src.Api.Ddlstreamitaly import search as ddlstreamitaly_film_serie
from Src.Api.Guardaserie import search as guardaserie_serie
# Config # Config
CLOSE_CONSOLE = config_manager.get_bool('DEFAULT', 'not_close') CLOSE_CONSOLE = config_manager.get_bool('DEFAULT', 'not_close')
def run_function(func: Callable[..., None], close_console: bool = False) -> None: def run_function(func: Callable[..., None], close_console: bool = False) -> None:
""" """
Run a given function indefinitely or once, depending on the value of close_console. Run a given function indefinitely or once, depending on the value of close_console.
@ -44,6 +39,56 @@ def run_function(func: Callable[..., None], close_console: bool = False) -> None
func() func()
def load_search_functions():
loaded_functions = {}
# Traverse the Api directory
api_dir = os.path.join(os.path.dirname(__file__), 'Src', 'Api')
init_files = glob.glob(os.path.join(api_dir, '*', '__init__.py'))
modules = []
# Retrieve modules and their indices
for init_file in init_files:
module_name = os.path.basename(os.path.dirname(init_file)) # Get folder name as module name
try:
# Dynamically import the module
mod = importlib.import_module(f'Src.Api.{module_name}')
# Get 'indice' from the module
indice = getattr(mod, 'indice', 0) # If 'indice' is not defined, default to 0
# Add module and indice to the list
modules.append((module_name, indice))
except Exception as e:
console.print(f"[red]Failed to import module {module_name}: {str(e)}")
# Sort modules by 'indice'
modules.sort(key=lambda x: x[1])
# Load search functions in the sorted order
for module_name, _ in modules:
module_alias = f'{module_name}_search' # Construct a unique alias for the module
try:
# Dynamically import the module
mod = importlib.import_module(f'Src.Api.{module_name}')
# Get the search function from the module (assuming the function is named 'search' and defined in __init__.py)
search_function = getattr(mod, 'search')
# Add the function to the loaded functions dictionary
loaded_functions[module_alias] = search_function
except Exception as e:
console.print(f"[red]Failed to load search function from module {module_name}: {str(e)}")
return loaded_functions
def initialize(): def initialize():
""" """
Initialize the application. Initialize the application.
@ -68,66 +113,56 @@ def initialize():
sys.exit(0) sys.exit(0)
# Attempting GitHub update # Attempting GitHub update
"""try: try:
git_update() git_update()
except Exception as e: except Exception as e:
console.print(f"[blue]Req github [white]=> [red]Failed: {e}")""" console.print(f"[blue]Req github [white]=> [red]Failed: {e}")
def main(): def main():
# Load search functions
search_functions = load_search_functions()
initialize() # Create dynamic argument parser
# Parse command line arguments
parser = argparse.ArgumentParser(description='Script to download film and series from the internet.') parser = argparse.ArgumentParser(description='Script to download film and series from the internet.')
parser.add_argument('-sa', '--streaming_anime', action='store_true', help='')
parser.add_argument('-sf', '--streaming_film', action='store_true', help='') # Add dynamic arguments based on loaded search modules
for alias in search_functions.keys():
short_option = alias[:3].upper() # Take the first three letters of the alias in uppercase
long_option = alias # Use the full alias as the full option name
parser.add_argument(f'-{short_option}', f'--{long_option}', action='store_true', help=f'Search for {alias.split("_")[0]} on streaming platforms.')
# Parse command line arguments
args = parser.parse_args() args = parser.parse_args()
# Mapping command-line arguments to functions # Mapping command-line arguments to functions
arg_to_function = { arg_to_function = {alias: search_functions[alias] for alias in search_functions.keys()}
'streaming_anime': streamingcommunity_anime,
'streaming_film': streamingcommunity_film_serie,
}
# Check which argument is provided and run the corresponding function # Check which argument is provided and run the corresponding function
for arg, func in arg_to_function.items(): for arg, func in arg_to_function.items():
if getattr(args, arg): if getattr(args, arg):
run_function(func, CLOSE_CONSOLE) run_function(func)
return return
# Mapping user input to functions # Mapping user input to functions
input_to_function = { input_to_function = {str(i): search_functions[alias] for i, alias in enumerate(search_functions.keys())}
'0': streamingcommunity_film_serie,
'1': streamingcommunity_anime,
'2': altadefinizione_film,
'3': ddlstreamitaly_film_serie,
'4': guardaserie_serie,
}
# Create dynamic prompt message and choices # Create dynamic prompt message and choices
choices = list(input_to_function.keys()) choice_labels = {str(i): alias.split("_")[0].capitalize() for i, alias in enumerate(search_functions.keys())}
choice_labels = { prompt_message = f"Insert category [white]({', '.join([f'[red]{key}: [magenta]{label}' for key, label in choice_labels.items()])}[white]): "
'0': "Streamingcommunity",
'1': "Animeunity",
'2': "Altadefinizione",
'3': "Ddlstreamitaly",
'4': "Guardaserie",
}
prompt_message = "[cyan]Insert category [white](" + ", ".join(
f"[red]{key}[white]: [bold magenta]{label}[white]" for key, label in choice_labels.items()
) + ")[white]:[/cyan]"
# Ask the user for input # Ask the user for input
category = msg.ask(prompt_message, choices=choices, default="0") category = msg.ask(prompt_message, choices=list(choice_labels.keys()), default="0")
# 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:
run_function(input_to_function[category], CLOSE_CONSOLE) run_function(input_to_function[category])
else: else:
console.print("[red]Invalid category.") console.print("[red]Invalid category.")
sys.exit(0) sys.exit(0)
if __name__ == '__main__': if __name__ == '__main__':
initialize()
main() main()