loader image

Reply To: How to Stop Ad Blocker Detection on Websites Like YouTube

What makes us different from other similar websites? Forums Tech How to Stop Ad Blocker Detection on Websites Like YouTube Reply To: How to Stop Ad Blocker Detection on Websites Like YouTube

#8068
thumbtak
Keymaster

Here is a script that downloads videos from YouTube, plays them in smplayer, and deletes the video after it is done. This will also remove sponsor ads and other ads.

1. $ sudo apt install smplayer
2. Check “Options => Preferences => Video => Start video in fullscreen”
3. Check “Options => Preferences => General => Close when finished playback”
4. $ mkdir ~/Documents/Scripts
5. $ cd ~/Documents/Scripts
6. $ mousepad YouTube-Ad-Free.sh
7. Use the script below:

#!/bin/bash

# ASCII Art Functions
# Function to print the main ASCII art banner for the script.
print_banner() {
echo "+---------------------------------+"
echo "|===========TAKS SHACK============|"
echo "|======https://taksshack.com======|"
echo "+---------------------------------+"

}

# Function to print a section header with ASCII art.
# Takes the section title as an argument.
print_section_header() {
echo "---=[ $@ ]=---------------------------------------------------"
echo ""
}

# --- Configuration ---
# URL to download the latest yt-dlp binary (Linux/macOS)
YTDLP_URL="https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp"
# Local path where yt-dlp will be saved and executed from
YTDLP_BIN="./yt-dlp"
# Name of the temporary Python script that will handle the download, play, and delete logic
PYTHON_SCRIPT="yt_dlp_player.py"
# Base name for the downloaded video file (e.g., "downloaded_video.mp4")
# yt-dlp will append the correct extension.
OUTPUT_BASENAME="downloaded_video"
# File to store the last used save folder
LAST_SAVE_FOLDER_FILE=".last_save_folder" # This file will now be conditionally deleted in cleanup
# Flag file to indicate if audio tools were installed by this script
AUDIO_TOOLS_INSTALLED_FLAG=".audio_tools_installed_by_script_flag"

# --- Main Script Execution ---

print_banner
print_section_header "SYSTEM SETUP"

# Step 1: Download yt-dlp if it doesn't exist or isn't executable
if [ ! -f "$YTDLP_BIN" ] || [ ! -x "$YTDLP_BIN" ]; then
echo " yt-dlp binary not found or not executable. Attempting to download..."
if command -v curl &> /dev/null; then
echo " Using 'curl' to download yt-dlp..."
curl -L "$YTDLP_URL" -o "$YTDLP_BIN"
elif command -v wget &> /dev/null; then
echo " Using 'wget' to download yt-dlp..."
wget -O "$YTDLP_BIN" "$YTDLP_URL"
else
echo " Error: Neither 'curl' nor 'wget' found. Please install one of them to download yt-dlp."
echo " Exiting script."
exit 1
fi

if [ $? -eq 0 ]; then
chmod +x "$YTDLP_BIN"
echo " yt-dlp downloaded and made executable."
else
echo " Error: Failed to download yt-dlp. Please check your internet connection or the URL."
echo " Exiting script."
exit 1
fi
else
echo " yt-dlp binary already exists and is executable. Skipping download."
fi

# Step 2: Check and install espeak-ng and aplay if not present
ESPEAK_NG_INSTALLED=false
APLAY_INSTALLED=false

if command -v espeak-ng &> /dev/null; then
ESPEAK_NG_INSTALLED=true
echo " espeak-ng is already installed."
else
echo " espeak-ng is NOT found."
fi

if command -v aplay &> /dev/null; then
APLAY_INSTALLED=true
echo " aplay is already installed."
else
echo " aplay is NOT found."
fi

# If either is missing, offer to install
if [ "$ESPEAK_NG_INSTALLED" = false ] || [ "$APLAY_INSTALLED" = false ]; then
read -p " Audio wake-up tools (espeak-ng, aplay) are missing. Do you want to install them? (y/n): " install_audio_tools_choice
if [[ "$install_audio_tools_choice" =~ ^[Yy]$ ]]; then
echo " Attempting to install audio tools..."
INSTALL_CMD=""
if command -v apt &> /dev/null; then
INSTALL_CMD="sudo apt install -y espeak-ng alsa-utils"
elif command -v dnf &> /dev/null; then
INSTALL_CMD="sudo dnf install -y espeak-ng alsa-utils"
elif command -v pacman &> /dev/null; then
INSTALL_CMD="sudo pacman -S --noconfirm espeak-ng alsa-utils"
else
echo " Error: No supported package manager (apt, dnf, pacman) found for installing audio tools."
echo " Please install espeak-ng and alsa-utils manually."
fi

if [ -n "$INSTALL_CMD" ]; then
if eval "$INSTALL_CMD"; then
echo " Audio tools installed successfully."
touch "$AUDIO_TOOLS_INSTALLED_FLAG" # Create flag file
else
echo " Error: Failed to install audio tools. Please check permissions or internet connection."
fi
fi
else
echo " Skipping audio tools installation. Audio wake-up feature may not work."
fi
fi

echo "" # Add a newline for better readability

# Removed the direct read of LAST_SAVE_FOLDER into a bash variable here,
# as the Python script will now handle reading it dynamically from the file.
# The environment variable is no longer strictly necessary for this purpose,
# but keeping it doesn't harm.

print_section_header "PYTHON SCRIPT CREATION"
# Step 3: Create the Python script dynamically
echo " Creating temporary Python script: $PYTHON_SCRIPT"
cat <<'EOF' > "$PYTHON_SCRIPT"
import subprocess
import os
import sys
import glob
import re
import time
import shutil

# Path to the downloaded yt-dlp binary (relative to where the shell script runs)
YTDLP_PATH = "./yt-dlp"
# Base name for the downloaded video file
OUTPUT_BASENAME = "downloaded_video"
# File to store the last used save folder (Python will now read/write this directly)
LAST_SAVE_FOLDER_FILE = ".last_save_folder"
# Temporary WAV file for the test sound
TEST_SOUND_FILE = "taks_shack_test_sound.wav"

# Exit code signaling to the bash script to uninstall audio tools and clean up last save folder
UNINSTALL_AUDIO_TOOLS_EXIT_CODE = 5

# Regex to find percentage in yt-dlp download lines
PROGRESS_RE = re.compile(r'\[download\]\s+(\d+\.?\d*)%')

def print_ascii_line(char='-', length=60):
"""Prints a line of ASCII characters."""
print(char * length)

def print_ascii_header(text, char='='):
"""Prints a header with ASCII art."""
print_ascii_line(char)
print(f" {text}")
print_ascii_line(char)
print("") # Add a newline for spacing

def draw_ascii_progress_bar(percentage, bar_length=40):
"""
Draws an ASCII progress bar for the download.
Updates the same line in the terminal using carriage return.
"""
filled_len = int(bar_length * percentage // 100)
bar = '#' * filled_len + '-' * (bar_length - filled_len)
sys.stdout.write(f'\rDownloading: [ {bar} ] {percentage:6.2f}%') # Fixed width for percentage
sys.stdout.flush()

def play_test_sound():
"""
Generates and plays a small test sound using espeak-ng and aplay.
"""
print_ascii_header("AUDIO TEST", '-')
test_text = "Initiating video playback. Stand by."

# Check if espeak-ng and aplay are available before attempting to play
if not (subprocess.run(["which", "espeak-ng"], capture_output=True).returncode == 0 and \
subprocess.run(["which", "aplay"], capture_output=True).returncode == 0):
print(" Skipping audio test: espeak-ng or aplay not found (or not in PATH).")
print_ascii_line('=')
return

try:
# Generate the WAV file
print(f" Generating test sound: '{test_text}'...")
subprocess.run(["espeak-ng", "-w", TEST_SOUND_FILE, test_text], check=True, capture_output=True)

# Play the WAV file
print(f" Playing test sound from {TEST_SOUND_FILE}...")
subprocess.run(["aplay", TEST_SOUND_FILE], check=True, capture_output=True)
print(" Test sound played successfully.")
except FileNotFoundError as e:
print(f" Warning: Audio test tools not found. {e.strerror}: '{e.filename}'.")
print(" This should have been caught by the main bash script. Audio wake-up may be unavailable.")
except subprocess.CalledProcessError as e:
print(f" Warning: Failed to generate or play test sound. Error: {e.stderr.decode().strip()}")
print(" Audio wake-up might not function correctly.")
except Exception as e:
print(f" An unexpected error occurred during audio test: {e}")
finally:
# Clean up the temporary sound file
if os.path.exists(TEST_SOUND_FILE):
os.remove(TEST_SOUND_FILE)
print_ascii_line('=') # Separator line

def run_yt_dlp(youtube_link, cookie_option=None, is_browser_option=False):
"""
Attempts to download a video using yt-dlp with optional cookies.
Prints download progress to stdout using a custom ASCII bar.
Returns (success_boolean, stderr_output, video_title_suggestion).
"""
# Use --get-filename to preview the filename yt-dlp would use
# Also use --get-title to get the actual title from YouTube
info_command = [
YTDLP_PATH,
'--get-title',
'--print', '%(title)s', # Get title
'--print', '%(id)s.%(ext)s', # Get filename suggestion
youtube_link
]
if cookie_option:
if is_browser_option:
info_command.extend(['--cookies-from-browser', cookie_option])
else:
expanded_cookies_path = os.path.expanduser(cookie_option)
info_command.extend(['--cookies', expanded_cookies_path])

video_title = None
suggested_filename = None
try:
info_process = subprocess.run(info_command, capture_output=True, text=True, check=True)
# Assuming yt-dlp prints title on first line, filename on second
info_lines = info_process.stdout.strip().split('\n')
if len(info_lines) >= 2:
video_title = info_lines[0].strip()
# Sanitize the title for use as a filename
suggested_filename = re.sub(r'[\\/:*?"<>|]', '_', video_title)
# Remove leading/trailing spaces, and ensure it's not empty
suggested_filename = suggested_filename.strip()
if not suggested_filename:
suggested_filename = "youtube_video" # Fallback if title is empty after sanitization

# Append a generic extension for the prompt, actual extension will be handled by yt-dlp
suggested_filename += ".mp4"
else:
print(f"Warning: Could not get full video info. Output: {info_process.stdout.strip()}")
except subprocess.CalledProcessError as e:
print(f"Error getting video info: {e.stderr}")
# Continue without title/filename if info gathering fails
except Exception as e:
print(f"An unexpected error occurred while getting video info: {e}")

download_command = [
YTDLP_PATH,
'--output', f"{OUTPUT_BASENAME}.%(ext)s",
'--merge-output-format', 'mp4',
'--sponsorblock-remove', 'sponsor',
youtube_link
]

# Add cookies option based on whether it's a browser or a file path
if cookie_option:
if is_browser_option:
download_command.extend(['--cookies-from-browser', cookie_option])
else:
# Expand user's home directory (e.g., '~/.config/cookies.txt')
expanded_cookies_path = os.path.expanduser(cookie_option)
download_command.extend(['--cookies', expanded_cookies_path])

stderr_output = ""
try:
# Use subprocess.Popen to stream output in real-time
process = subprocess.Popen(
download_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True, # Decode stdout/stderr as text
bufsize=1 # Line-buffered output for real-time printing
)

is_download_progress_active = False
# Read stdout line by line
for line in iter(process.stdout.readline, ''):
# Check if the line is a progress update from yt-dlp
match = PROGRESS_RE.search(line)
if match:
is_download_progress_active = True
percentage = float(match.group(1))
draw_ascii_progress_bar(percentage)
else:
# If a progress bar was active, print a newline before other output
# to prevent other messages from overwriting the bar.
if is_download_progress_active:
sys.stdout.write('\n') # Move to next line after progress bar
is_download_progress_active = False
sys.stdout.write(line) # Print other yt-dlp output directly
sys.stdout.flush()

# After the loop, if a progress bar was the last thing printed, ensure a newline
# so the next output starts on a fresh line.
if is_download_progress_active:
sys.stdout.write('\n')
# The flag <code>is_download_progress_active</code> is reset by the shell script's cleanup

# Read any remaining content from stderr (usually error messages)
stderr_output = process.stderr.read()

# Wait for the subprocess to complete and get its return code
return_code = process.wait()
return return_code == 0, stderr_output, suggested_filename
except FileNotFoundError:
return False, f"Error: yt-dlp binary not found at '{YTDLP_PATH}'. Ensure it's downloaded and executable.", suggested_filename
except Exception as e:
return False, f"An unexpected error occurred during yt-dlp execution: {e}", suggested_filename

def download_and_play_video():
"""
Prompts for a YouTube link, attempts to download the video (with cookie retry logic),
plays it, and then handles saving/deleting based on user choice.
Returns True if video processing was completed (saved or deleted), False otherwise.
"""
final_video_file = None # Initialize to None to ensure it's always defined for cleanup

# --- NEW: Read last_save_folder directly from the file in Python every time ---
last_save_folder = ""
if os.path.exists(LAST_SAVE_FOLDER_FILE):
try:
with open(LAST_SAVE_FOLDER_FILE, 'r') as f:
last_save_folder = f.read().strip()
except Exception as e:
print(f"Warning: Could not read last save folder file '{LAST_SAVE_FOLDER_FILE}': {e}")
last_save_folder = "" # Reset if read fails

try:
# --- Pre-flight Checks (for Python specific dependencies) ---
print_ascii_header("PYTHON DEPENDENCY CHECKS", '-')
# 1. Check if smplayer is installed and accessible in the system's PATH.
sys.stdout.write(" Checking for smplayer...")
sys.stdout.flush() # Ensure message is displayed immediately
if subprocess.run(["which", "smplayer"], capture_output=True).returncode != 0:
print(" [FAILED]")
print(" Error: 'smplayer' is not found in your system's PATH.")
print(" Please ensure smplayer is installed and its executable is in your PATH.")
sys.exit(1) # Exit if smplayer is not found
print(" [OK]")

# 2. Check if the yt-dlp binary exists and is executable.
sys.stdout.write(f" Checking for yt-dlp at '{YTDLP_PATH}'...")
sys.stdout.flush() # Ensure message is displayed immediately
if not os.path.exists(YTDLP_PATH) or not os.access(YTDLP_PATH, os.X_OK):
print(" [FAILED]")
print(f" Error: yt-dlp not found or not executable at '{YTDLP_PATH}'.")
print(" Please ensure the shell script has successfully downloaded and set permissions for yt-dlp.")
sys.exit(1) # Exit if yt-dlp is not ready
print(" [OK]")
print_ascii_line('=') # Separator line

# --- User Input ---
print_ascii_header("VIDEO LINK", '-')
youtube_link = input(" Please enter the YouTube video link: ")
if not youtube_link:
print(" No link entered. Exiting video processing.")
return False # Indicate that no video was processed

print_ascii_header(f"PROCESSING: {youtube_link}", '=')

download_attempt_successful = False
suggested_filename_for_save = None

# --- First Video Download Attempt (without cookies) ---
print("\n Attempting to download video without cookies...")
success, stderr, suggested_filename_for_save = run_yt_dlp(youtube_link)

if success:
download_attempt_successful = True
print("\n Video download completed successfully.")
else:
print("\n Initial video download failed.")
print(" yt-dlp output (stderr):\n" + stderr) # Show error for debugging

# Check if error output suggests cookies might be needed for authentication
needs_cookie_keywords = [
"private video", "age restricted", "login required",
"sign in", "authentication", "cookies", "access denied"
]
should_suggest_cookies = any(keyword in stderr.lower() for keyword in needs_cookie_keywords)

if should_suggest_cookies:
retry_choice = input(
"\n The download failed, possibly due to requiring authentication or cookies. "
"Do you want to try again (y/n)? "
).lower()

if retry_choice == 'y':
cookie_method_choice = input(
" How do you want to provide cookies?\n"
" 1. From a browser (e.g., firefox, chrome)\n"
" 2. From a cookies.txt file\n"
" Enter 1 or 2: "
).strip()

cookie_option_value = None
is_browser = False

if cookie_method_choice == '1':
browser_options = {
1: "firefox", 2: "chrome", 3: "chromium",
4: "brave", 5: "edge", 6: "opera",
7: "safari", 8: "vivaldi", 9: "librewolf"
}
print("\n Select a browser for cookies:")
for num, browser in browser_options.items():
print(f" {num}. {browser.capitalize()}")

browser_selection_input = input(" Enter the number of your preferred browser: ").strip()
try:
browser_selection_num = int(browser_selection_input)
if browser_selection_num in browser_options:
browser_name = browser_options[browser_selection_num]
cookie_option_value = browser_name
is_browser = True
print(f"\n Attempting to download video using cookies from {browser_name}...")
else:
print(" Invalid browser number. Falling back to cookies.txt file option.")
cookie_method_choice = '2' # Fallback to file option
except ValueError:
print(" Invalid input. Please enter a number. Falling back to cookies.txt file option.")
cookie_method_choice = '2' # Fallback to file option

if cookie_method_choice == '2' or (cookie_method_choice == '1' and not is_browser): # Fallback or direct choice for file
cookies_file_path = input(
" Please enter the path to the cookies file "
"(e.g., ~/.config/yt-dlp/cookies.txt or cookies.txt in current directory): "
).strip()
if cookies_file_path:
cookie_option_value = cookies_file_path
is_browser = False # Explicitly set to false for file path
print("\n Attempting to download video with cookies from file...")
else:
print(" No cookies file path provided. Cannot retry with cookies.")

if cookie_option_value:
success_retry, stderr_retry, suggested_filename_for_save = run_yt_dlp(youtube_link, cookie_option_value, is_browser)

if success_retry:
download_attempt_successful = True
print("\n Video download completed with cookies.")
else:
print(" Video download failed even with cookies.")
print(" yt-dlp output (stderr with cookies):\n" + stderr_retry)
else:
print(" No valid cookie option provided. Cannot retry with cookies.")
else:
print(" Not retrying. Exiting video processing.")
else:
print(" Download failed for reasons not immediately indicating a cookie requirement.")

if not download_attempt_successful:
print("\n Failed to download video. Exiting script.")
return False # Indicate that no video was processed successfully

# --- Find Downloaded File ---
print_ascii_header("LOCATING VIDEO", '-')
sys.stdout.write(" Searching for downloaded video file...")
sys.stdout.flush()
downloaded_files = glob.glob(f"{OUTPUT_BASENAME}.*")

# Filter for the most likely playable video file. Prioritize common video extensions.
for f in downloaded_files:
if f.startswith(OUTPUT_BASENAME) and (f.endswith(".mp4") or f.endswith(".webm") or f.endswith(".mkv")):
final_video_file = f
break # Found a suitable file, exit loop

if not final_video_file:
print(" [NOT FOUND]")
print(f" Error: Could not find a video file matching '{OUTPUT_BASENAME}.*' after download.")
print(f" Please check the directory for downloaded files. Found: {downloaded_files}")
return False # Indicate failure

print(" [FOUND]")
print(f" Identified downloaded video file: {final_video_file}")
print_ascii_line('=') # Separator line

# --- Play Test Sound before Video ---
# The bash script ensures espeak-ng/aplay are installed if user opted for it
play_test_sound()

# --- Play Video ---
print_ascii_header("PLAYING VIDEO", '-')
print(f" Playing video with smplayer: {final_video_file}")
subprocess.run(["smplayer", final_video_file], check=True) # Execute smplayer
print(" Video playback finished.")
print_ascii_line('=') # Separator line

# --- Save Video Logic ---
print_ascii_header("SAVE VIDEO", '-')
save_choice = input(f" Do you want to save this video (current name: '{suggested_filename_for_save if suggested_filename_for_save else final_video_file}')? (y/n): ").lower()

if save_choice == 'y':
# Ask for new filename, default to YouTube's title
new_filename = input(f" Enter the desired filename (default: '{suggested_filename_for_save}'): ").strip()
if not new_filename:
new_filename = suggested_filename_for_save

# Ensure the new filename has an extension
if not os.path.splitext(new_filename)[1]:
# Get the extension from the downloaded file
original_ext = os.path.splitext(final_video_file)[1]
new_filename += original_ext

# Ask for save folder
target_folder = ""
if last_save_folder and os.path.isdir(last_save_folder):
use_previous_folder = input(f" Use previous save folder '{last_save_folder}'? (y/n): ").lower()
if use_previous_folder == 'y':
target_folder = last_save_folder
else:
target_folder = input(" Enter the new save folder path: ").strip()
else:
target_folder = input(" Enter the save folder path: ").strip()

if not target_folder:
print(" No save folder specified. Video will not be saved.")
os.remove(final_video_file) # Delete if user decides not to save after all
print(f" Deleted unsaved video: {final_video_file}")
return True # Indicate that the process was handled, but video not saved

# Ensure target folder exists
os.makedirs(target_folder, exist_ok=True)

destination_path = os.path.join(target_folder, new_filename)
try:
# Using shutil.move for cross-device compatibility
shutil.move(final_video_file, destination_path)
print(f" Video saved successfully to: {destination_path}")
# Update last save folder file (now this update will be effective for next loop iteration)
with open(LAST_SAVE_FOLDER_FILE, 'w') as f:
f.write(target_folder)
print(f" Last save folder updated to: {target_folder}")
except OSError as e:
print(f" Error saving video: {e}")
print(f" The video was not moved. It remains as '{final_video_file}' in the current directory.")
# Don't delete, let the user manually handle if move failed
print_ascii_line('=') # Separator line
else:
print(" Video will not be saved.")
# --- Delete Downloaded Video if not saved ---
if final_video_file and os.path.exists(final_video_file):
try:
os.remove(final_video_file)
print(f" Successfully deleted unsaved video: {final_video_file}")
except Exception as e:
print(f" Warning: Could not delete {final_video_file}. Reason: {e}")
print(" It might be in use or permissions are incorrect.")
print_ascii_line('=') # Separator line

return True # Indicate that the video processing was completed (either saved or deleted)

except FileNotFoundError as e:
print_ascii_header("RUNTIME ERROR", '#')
print(f" Runtime Error: A required command was not found. Detail: {e}")
print(" Please ensure all necessary applications (smplayer, curl/wget, python3) are installed and in your system's PATH.")
return False # Indicate failure
except subprocess.CalledProcessError as e:
print_ascii_header("EXECUTION ERROR", '#')
print(f" Command Execution Error (Exit code: {e.returncode}):")
print(f" Command: {' '.join(e.cmd)}")
if e.stdout:
print(f" Stdout: {e.stdout.decode('utf-8')}")
if e.stderr:
print(f" Stderr: {e.stderr.decode('utf-8')}")
print(" Please review the error messages above for details on what went wrong.")
return False # Indicate failure
except Exception as e:
print_ascii_header("UNEXPECTED ERROR", '#')
print(f" An unexpected error occurred: {e}")
return False # Indicate failure
finally:
# Aggressive cleanup of any residual 'downloaded_video.*' files that might be left over
# This acts as a fallback if explicit deletion failed or was skipped
print_ascii_header("FINAL CLEANUP OF TEMP FILES", '-')
print(" Checking for residual temporary files...")
for f in glob.glob(f"{OUTPUT_BASENAME}.*"):
if os.path.exists(f): # Ensure file still exists before trying to remove
try:
os.remove(f)
print(f" Cleaned up residual temporary file: {f}")
except Exception as e:
print(f" Warning: Could not clean up residual temporary file {f}. Reason: {e}")
# Also clean up the test sound file if for some reason it wasn't already removed
if os.path.exists(TEST_SOUND_FILE):
try:
os.remove(TEST_SOUND_FILE)
print(f" Cleaned up temporary sound file: {TEST_SOUND_FILE}")
except Exception as e:
print(f" Warning: Could not clean up temporary sound file {TEST_SOUND_FILE}. Reason: {e}")

print_ascii_line('=') # Separator line

# Ensure the main function is called when the script is executed.
if __name__ == "__main__":
while True:
video_processed_successfully = download_and_play_video()

watch_another = input("\n Would you like to watch another YouTube video? (y/n): ").lower()
if watch_another != 'y':
print(" Exiting. Goodbye!")
sys.exit(UNINSTALL_AUDIO_TOOLS_EXIT_CODE) # Signal bash script to uninstall
# If 'y', loop continues, nothing special to exit with.
EOF

echo "" # Add a newline for better readability

print_section_header "RUNNING PLAYER"
# Step 4: Run the Python script
echo " Executing Python script: $PYTHON_SCRIPT"
# The Python script will now handle the loop and exit with a specific code when the user is done.
python3 "$PYTHON_SCRIPT"
PYTHON_EXIT_CODE=$? # Capture the exit code of the Python script

echo "" # Add a newline for better readability

print_section_header "FINAL CLEANUP"
# Step 5: Clean up temporary files and potentially uninstall audio tools
echo " Cleaning up shell script's temporary files..."

# Remove the temporary Python script
if [ -f "$PYTHON_SCRIPT" ]; then
rm "$PYTHON_SCRIPT"
echo " Removed temporary Python script: $PYTHON_SCRIPT"
fi

# Remove the yt-dlp binary as requested
if [ -f "$YTDLP_BIN" ]; then
rm "$YTDLP_BIN"
echo " Removed yt-dlp binary: $YTDLP_BIN"
fi

# Condition for removing the last save folder file: only if Python script exited with 'no more videos' signal
if [ $PYTHON_EXIT_CODE -eq 5 ] && [ -f "$LAST_SAVE_FOLDER_FILE" ]; then
rm "$LAST_SAVE_FOLDER_FILE"
echo " Removed last save folder file: $LAST_SAVE_FOLDER_FILE (as requested upon exit)"
elif [ -f "$LAST_SAVE_FOLDER_FILE" ]; then
echo " Keeping last save folder file: $LAST_SAVE_FOLDER_FILE (script did not exit via 'no more videos' option)"
fi

# Check if the Python script signaled for audio tool uninstallation
# And if the flag file exists (meaning *this* script installed them)
if [ $PYTHON_EXIT_CODE -eq 5 ] && [ -f "$AUDIO_TOOLS_INSTALLED_FLAG" ]; then
echo ""
read -p " This script installed 'espeak-ng' and 'alsa-utils'. Do you want to uninstall them now? (y/n): " uninstall_confirm
if [[ "$uninstall_confirm" =~ ^[Yy]$ ]]; then
echo " Attempting to uninstall audio tools..."
UNINSTALL_CMD=""
if command -v apt &> /dev/null; then
UNINSTALL_CMD="sudo apt remove -y espeak-ng alsa-utils"
elif command -v dnf &> /dev/null; then
UNINSTALL_CMD="sudo dnf remove -y espeak-ng alsa-utils"
elif command -v pacman &> /dev/null; then
UNINSTALL_CMD="sudo pacman -R --noconfirm espeak-ng alsa-utils"
else
echo " Error: No supported package manager found for uninstalling audio tools."
echo " Please install espeak-ng and alsa-utils manually."
fi

if [ -n "$UNINSTALL_CMD" ]; then
if eval "$UNINSTALL_CMD"; then
echo " Audio tools uninstalled successfully."
rm "$AUDIO_TOOLS_INSTALLED_FLAG" # Remove flag file
else
echo " Error: Failed to uninstall audio tools. Please check permissions."
fi
fi
else
echo " Skipping audio tools uninstallation."
fi
elif [ $PYTHON_EXIT_CODE -eq 5 ]; then
echo " Audio tools uninstallation not requested as they were not installed by this script."
fi

# Report final status based on the Python script's exit code
if [ $PYTHON_EXIT_CODE -ne 0 ] && [ $PYTHON_EXIT_CODE -ne 5 ]; then
echo " Script finished with errors (exit code: $PYTHON_EXIT_CODE)."
exit $PYTHON_EXIT_CODE
else
echo " Script finished successfully."
exit 0
fi

8. $ bash YouTube-Ad-Free.sh

  • This reply was modified 1 week, 4 days ago by thumbtak.
  • This reply was modified 1 week, 2 days ago by thumbtak. Reason: Updated script to include, cookie grabbing, if needed, with percent for download, and changed it to delete yt-dlp file left behind in the old script
  • This reply was modified 1 week, 1 day ago by thumbtak. Reason: Beautification
  • This reply was modified 2 days, 4 hours ago by thumbtak. Reason: TTS added to wake up some speakers, Watch another video question, save video to location question
  • This reply was modified 2 days, 4 hours ago by thumbtak. Reason: Bugfix
  • This reply was modified 2 days ago by thumbtak. Reason: Saves location where you last saved the file. When the you saw no, to another, it will remove the saved location
  • This reply was modified 1 day, 23 hours ago by thumbtak.
TAKs Shack