Add generic display_episodes_list

This commit is contained in:
Dark1291 2025-02-11 14:57:34 +01:00
parent 3bf63e9166
commit d640284b92
8 changed files with 95 additions and 153 deletions

View File

@ -1,7 +1,6 @@
# 13.06.24 # 13.06.24
import os import os
import sys
from urllib.parse import urlparse from urllib.parse import urlparse
from typing import Tuple from typing import Tuple
@ -10,13 +9,17 @@ from typing import Tuple
from StreamingCommunity.Util.console import console from StreamingCommunity.Util.console import console
from StreamingCommunity.Util.message import start_message from StreamingCommunity.Util.message import start_message
from StreamingCommunity.Util.os import os_manager from StreamingCommunity.Util.os import os_manager
from StreamingCommunity.Util.table import TVShowManager
from StreamingCommunity.Lib.Downloader import MP4_downloader from StreamingCommunity.Lib.Downloader import MP4_downloader
# Logic class # Logic class
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
from StreamingCommunity.Api.Template.Util import manage_selection, map_episode_title, validate_episode_selection from StreamingCommunity.Api.Template.Util import (
manage_selection,
map_episode_title,
validate_episode_selection,
display_episodes_list
)
# Player # Player
@ -111,39 +114,3 @@ def download_thread(dict_serie: MediaItem):
if kill_handler: if kill_handler:
break break
kill_handler = download_video(i_episode, scape_info_serie, video_source)[1] kill_handler = download_video(i_episode, scape_info_serie, video_source)[1]
def display_episodes_list(obj_episode_manager) -> str:
"""
Display episodes list and handle user input.
Returns:
last_command (str): Last command entered by the user.
"""
# Set up table for displaying episodes
table_show_manager = TVShowManager()
table_show_manager.set_slice_end(10)
# Add columns to the table
column_info = {
"Index": {'color': 'red'},
"Name": {'color': 'magenta'},
}
table_show_manager.add_column(column_info)
# Populate the table with episodes information
for i, media in enumerate(obj_episode_manager):
table_show_manager.add_tv_show({
'Index': str(i+1),
'Name': media.get('name'),
})
# Run the table and handle user input
last_command = table_show_manager.run()
if last_command == "q":
console.print("\n[red]Quit [white]...")
sys.exit(0)
return last_command

View File

@ -1,19 +1,24 @@
# 13.06.24 # 13.06.24
import os import os
import sys
from typing import Tuple from typing import Tuple
# 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.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 from StreamingCommunity.Api.Template.Util import (
manage_selection,
map_episode_title,
dynamic_format_number,
validate_selection,
validate_episode_selection,
display_episodes_list
)
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
@ -161,40 +166,4 @@ def download_series(dict_serie: MediaItem) -> None:
else: else:
# Otherwise, let the user select specific episodes for the single season # Otherwise, let the user select specific episodes for the single season
download_episode(scape_info_serie, i_season, download_all=False) download_episode(scape_info_serie, i_season, download_all=False)
def display_episodes_list(obj_episode_manager) -> str:
"""
Display episodes list and handle user input.
Returns:
last_command (str): Last command entered by the user.
"""
# Set up table for displaying episodes
table_show_manager = TVShowManager()
table_show_manager.set_slice_end(10)
# Add columns to the table
column_info = {
"Index": {'color': 'red'},
"Name": {'color': 'magenta'},
}
table_show_manager.add_column(column_info)
# Populate the table with episodes information
for media in obj_episode_manager:
table_show_manager.add_tv_show({
'Index': str(media.get('number')),
'Name': media.get('name'),
})
# Run the table and handle user input
last_command = table_show_manager.run()
if last_command == "q":
console.print("\n[red]Quit [white]...")
sys.exit(0)
return last_command

View File

@ -11,10 +11,15 @@ from bs4 import BeautifulSoup
# Internal utilities # Internal utilities
from StreamingCommunity.Util.headers import get_headers from StreamingCommunity.Util.headers import get_headers
from StreamingCommunity.Util._jsonConfig import config_manager
# Logic class # Logic class
from StreamingCommunity.Api.Template .Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
# Variable
max_timeout = config_manager.get_int("REQUESTS", "timeout")
class GetSerieInfo: class GetSerieInfo:
@ -40,19 +45,12 @@ class GetSerieInfo:
try: try:
# Make an HTTP request to the series URL # Make an HTTP request to the series URL
response = httpx.get(self.url, headers=self.headers, timeout=15) response = httpx.get(self.url, headers=self.headers, timeout=max_timeout, follow_redirects=True)
response.raise_for_status() response.raise_for_status()
# Parse HTML content of the page
soup = BeautifulSoup(response.text, "html.parser") soup = BeautifulSoup(response.text, "html.parser")
# Find the container of seasons
table_content = soup.find('div', class_="tt_season") table_content = soup.find('div', class_="tt_season")
# Count the number of seasons
seasons_number = len(table_content.find_all("li")) seasons_number = len(table_content.find_all("li"))
# Extract the name of the series
self.tv_name = soup.find("h1", class_="front_title").get_text(strip=True) self.tv_name = soup.find("h1", class_="front_title").get_text(strip=True)
return seasons_number return seasons_number
@ -60,7 +58,7 @@ class GetSerieInfo:
except Exception as e: except Exception as e:
logging.error(f"Error parsing HTML page: {e}") logging.error(f"Error parsing HTML page: {e}")
return -999 return -1
def get_episode_number(self, n_season: int) -> List[Dict[str, str]]: def get_episode_number(self, n_season: int) -> List[Dict[str, str]]:
""" """
@ -75,7 +73,7 @@ class GetSerieInfo:
try: try:
# Make an HTTP request to the series URL # Make an HTTP request to the series URL
response = httpx.get(self.url, headers=self.headers, timeout=15) response = httpx.get(self.url, headers=self.headers, timeout=max_timeout, follow_redirects=True)
response.raise_for_status() response.raise_for_status()
# Parse HTML content of the page # Parse HTML content of the page
@ -83,8 +81,6 @@ class GetSerieInfo:
# Find the container of episodes for the specified season # Find the container of episodes for the specified season
table_content = soup.find('div', class_="tab-pane", id=f"season-{n_season}") table_content = soup.find('div', class_="tab-pane", id=f"season-{n_season}")
# Extract episode information
episode_content = table_content.find_all("li") episode_content = table_content.find_all("li")
list_dict_episode = [] list_dict_episode = []
@ -107,4 +103,4 @@ class GetSerieInfo:
except Exception as e: except Exception as e:
logging.error(f"Error parsing HTML page: {e}") logging.error(f"Error parsing HTML page: {e}")
return [] return []

View File

@ -1,20 +1,25 @@
# 3.12.23 # 3.12.23
import os import os
import sys
from typing import Tuple from typing import Tuple
# 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.table import TVShowManager
from StreamingCommunity.Lib.Downloader import HLS_Downloader from StreamingCommunity.Lib.Downloader import HLS_Downloader
from StreamingCommunity.TelegramHelp.telegram_bot import TelegramSession, get_bot_instance from StreamingCommunity.TelegramHelp.telegram_bot import TelegramSession, get_bot_instance
# 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 from StreamingCommunity.Api.Template.Util import (
manage_selection,
map_episode_title,
dynamic_format_number,
validate_selection,
validate_episode_selection,
display_episodes_list
)
from StreamingCommunity.Api.Template.Class.SearchType import MediaItem from StreamingCommunity.Api.Template.Class.SearchType import MediaItem
@ -114,7 +119,7 @@ def download_episode(index_season_selected: int, scrape_serie: ScrapeSerie, vide
else: else:
# Display episodes list and manage user selection # Display episodes list and manage user selection
last_command = display_episodes_list(scrape_serie) last_command = display_episodes_list(scrape_serie.episode_manager.episodes)
list_episode_select = manage_selection(last_command, episodes_count) list_episode_select = manage_selection(last_command, episodes_count)
try: try:
@ -204,55 +209,4 @@ def download_series(select_season: MediaItem, version: str) -> None:
# Get script_id # Get script_id
script_id = TelegramSession.get_session() script_id = TelegramSession.get_session()
if script_id != "unknown": if script_id != "unknown":
TelegramSession.deleteScriptId(script_id) TelegramSession.deleteScriptId(script_id)
def display_episodes_list(scrape_serie) -> str:
"""
Display episodes list and handle user input.
Returns:
last_command (str): Last command entered by the user.
"""
if TELEGRAM_BOT:
bot = get_bot_instance()
# Set up table for displaying episodes
table_show_manager = TVShowManager()
table_show_manager.set_slice_end(10)
# Add columns to the table
column_info = {
"Index": {'color': 'red'},
"Name": {'color': 'magenta'},
"Duration": {'color': 'green'}
}
table_show_manager.add_column(column_info)
# Populate the table with episodes information
if TELEGRAM_BOT:
choices = []
for i, media in enumerate(scrape_serie.episode_manager.episodes):
table_show_manager.add_tv_show({
'Index': str(media.number),
'Name': media.name,
'Duration': str(media.duration)
})
if TELEGRAM_BOT:
choice_text = f"{media.number} - {media.name} ({media.duration} min)"
choices.append(choice_text)
if TELEGRAM_BOT:
if choices:
bot.send_message(f"Lista episodi:", choices)
# Run the table and handle user input
last_command = table_show_manager.run()
if last_command == "q" or last_command == "quit":
console.print("\n[red]Quit [white]...")
sys.exit(0)
return last_command

View File

@ -2,4 +2,11 @@
from .recall_search import execute_search from .recall_search import execute_search
from .get_domain import search_domain from .get_domain import search_domain
from .manage_ep import manage_selection, map_episode_title, validate_episode_selection, validate_selection, dynamic_format_number from .manage_ep import (
manage_selection,
map_episode_title,
validate_episode_selection,
validate_selection,
dynamic_format_number,
display_episodes_list
)

View File

@ -1,12 +1,15 @@
# 19.06.24 # 19.06.24
import sys
import logging import logging
from typing import List from typing import List
# Internal utilities # Internal utilities
from StreamingCommunity.Util._jsonConfig import config_manager from StreamingCommunity.Util.console import console
from StreamingCommunity.Util.os import os_manager from StreamingCommunity.Util.os import os_manager
from StreamingCommunity.Util._jsonConfig import config_manager
from StreamingCommunity.Util.table import TVShowManager
# Config # Config
@ -176,4 +179,45 @@ def validate_episode_selection(list_episode_select: List[int], episodes_count: i
# Prompt the user for valid input again # Prompt the user for valid input again
input_episodes = input(f"Enter valid episode numbers (1-{episodes_count}): ") input_episodes = input(f"Enter valid episode numbers (1-{episodes_count}): ")
list_episode_select = list(map(int, input_episodes.split(','))) list_episode_select = list(map(int, input_episodes.split(',')))
def display_episodes_list(episodes_manager) -> str:
"""
Display episodes list and handle user input.
Returns:
last_command (str): Last command entered by the user.
"""
# Set up table for displaying episodes
table_show_manager = TVShowManager()
table_show_manager.set_slice_end(10)
# Add columns to the table
column_info = {
"Index": {'color': 'red'},
"Name": {'color': 'magenta'},
"Duration": {'color': 'blue'}
}
table_show_manager.add_column(column_info)
# Populate the table with episodes information
for i, media in enumerate(episodes_manager):
name = media.get('name') if isinstance(media, dict) else getattr(media, 'name', None)
duration = media.get('duration') if isinstance(media, dict) else getattr(media, 'duration', None)
episode_info = {
'Index': str(i + 1),
'Name': name,
'Duration': duration
}
table_show_manager.add_tv_show(episode_info)
# Run the table and handle user input
last_command = table_show_manager.run()
if last_command in ("q", "quit"):
console.print("\n[red]Quit [white]...")
sys.exit(0)
return last_command

View File

@ -49,6 +49,7 @@ DEFAULT_AUDIO_WORKERS = config_manager.get_int('M3U8_DOWNLOAD', 'default_audio_w
MAX_TIMEOOUT = config_manager.get_int("REQUESTS", "timeout") MAX_TIMEOOUT = config_manager.get_int("REQUESTS", "timeout")
MAX_INTERRUPT_COUNT = 3 MAX_INTERRUPT_COUNT = 3
SEGMENT_MAX_TIMEOUT = config_manager.get_int("M3U8_DOWNLOAD", "segment_timeout") SEGMENT_MAX_TIMEOUT = config_manager.get_int("M3U8_DOWNLOAD", "segment_timeout")
TELEGRAM_BOT = config_manager.get_bool('DEFAULT', 'telegram_bot')
@ -324,6 +325,10 @@ 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'
""" """
if TELEGRAM_BOT:
# Viene usato per lo screen
console.log("####")
self.get_info() self.get_info()
self.setup_interrupt_handler() self.setup_interrupt_handler()

View File

@ -65,7 +65,7 @@
"domain": "pro" "domain": "pro"
}, },
"guardaserie": { "guardaserie": {
"domain": "meme" "domain": "now"
}, },
"mostraguarda": { "mostraguarda": {
"domain": "stream" "domain": "stream"