Added MP4 stop signal handler for series

This commit is contained in:
Gra 2025-02-01 10:12:22 +01:00
parent 535bc7b257
commit 8faeeefdd7
2 changed files with 53 additions and 14 deletions

View File

@ -24,10 +24,10 @@ from StreamingCommunity.Api.Player.vixcloud import VideoSourceAnime
# Variable
from .costant import SITE_NAME, ANIME_FOLDER, MOVIE_FOLDER
KILL_HANDLER = bool(False)
def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_source: VideoSourceAnime) -> str:
def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_source: VideoSourceAnime) -> tuple[str,bool]:
"""
Downloads the selected episode.
@ -36,6 +36,7 @@ def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_so
Return:
- str: output path
- bool: kill handler status
"""
# Get information about the selected episode
@ -45,7 +46,8 @@ def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_so
start_message()
console.print(f"[yellow]Download: [red]EP_{obj_episode.number} \n")
console.print("[cyan]You can safely stop the download with [bold]Ctrl+c[bold] [cyan] \n")
# Collect mp4 url
video_source.get_embed(obj_episode.id)
@ -65,11 +67,18 @@ def download_episode(index_select: int, scrape_serie: ScrapeSerieAnime, video_so
os_manager.create_path(mp4_path)
# Start downloading
r_proc = MP4_downloader(
url=str(video_source.src_mp4).strip(),
path=os.path.join(mp4_path, title_name)
)
# If download fails do not create the file
if r_proc == None:
if os.path.exists(os.path.join(mp4_path, title_name)):
os.remove(os.path.join(mp4_path, title_name))
return "",True
if r_proc != None:
console.print("[green]Result: ")
console.print(r_proc)
@ -106,12 +115,15 @@ def download_series(select_title: MediaItem):
# Download selected episodes
if len(list_episode_select) == 1 and last_command != "*":
download_episode(list_episode_select[0]-1, scrape_serie, video_source)
download_episode(list_episode_select[0]-1, scrape_serie, video_source)[0]
# Download all other episodes selecter
else:
kill_handler=bool(False)
for i_episode in list_episode_select:
download_episode(i_episode-1, scrape_serie, video_source)
if kill_handler:
break
kill_handler= download_episode(i_episode-1, scrape_serie, video_source)[1]
def download_film(select_title: MediaItem):

View File

@ -1,11 +1,12 @@
# 09.06.24
import os
import signal
import sys
import ssl
import certifi
import logging
import atexit
# External libraries
import httpx
@ -34,7 +35,9 @@ GET_ONLY_LINK = config_manager.get_bool('M3U8_PARSER', 'get_only_link')
TQDM_USE_LARGE_BAR = config_manager.get_int('M3U8_DOWNLOAD', 'tqdm_use_large_bar')
REQUEST_TIMEOUT = config_manager.get_float('REQUESTS', 'timeout')
#Ending constant
KILL_HANDLER = bool(False)
def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = None):
"""
@ -46,6 +49,7 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
- referer (str, optional): The referer header value.
- headers_ (dict, optional): Custom headers for the request.
"""
# Early return for link-only mode
if GET_ONLY_LINK:
return {'path': path, 'url': url}
@ -111,15 +115,34 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
# Ensure directory exists
os.makedirs(os.path.dirname(path), exist_ok=True)
def signal_handler(*args):
"""
Signal handler for SIGINT
Parameters:
- args (tuple): The signal arguments (to prevent errors).
"""
if(downloaded<total/2):
raise KeyboardInterrupt
else:
console.print("[bold green]Download almost completed, will exit next[/bold green]")
print("KILL_HANDLER: ", KILL_HANDLER)
# Download file
with open(path, 'wb') as file, progress_bar as bar:
downloaded = 0
for chunk in response.iter_bytes(chunk_size=1024):
if chunk:
size = file.write(chunk)
downloaded += size
bar.update(size)
#Test check stop download
#atexit.register(quit_gracefully)
for chunk in response.iter_bytes(chunk_size=1024):
signal.signal(signal.SIGINT,signal_handler)
if chunk:
size = file.write(chunk)
downloaded += size
bar.update(size)
# Optional: Add a check to stop download if needed
# if downloaded > MAX_DOWNLOAD_SIZE:
# break
@ -133,7 +156,7 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
title=f"{os.path.basename(path.replace('.mp4', ''))}",
border_style="green"
))
return path
return path,KILL_HANDLER
else:
console.print("[bold red]Download failed or file is empty.[/bold red]")
@ -153,3 +176,7 @@ def MP4_downloader(url: str, path: str, referer: str = None, headers_: dict = No
logging.error(f"Unexpected error during download: {e}")
console.print(f"[bold red]Unexpected Error: {e}[/bold red]")
return None
except KeyboardInterrupt:
console.print("[bold red]Download stopped by user.[/bold red]")
return None