Refactor CLI setup script, add prompts for muting and skipping native youtube ads

This commit is contained in:
Ryan Kupka
2024-05-03 10:18:16 -06:00
parent 80196b19aa
commit daa7026221

View File

@@ -1,167 +1,186 @@
import asyncio import asyncio
import aiohttp import aiohttp
from . import api_helpers, ytlounge from . import api_helpers, ytlounge
# Constants for user input prompts
async def pair_device(): ATVS_REMOVAL_PROMPT = (
try: "Do you want to remove the legacy 'atvs' entry (the app won't start"
lounge_controller = ytlounge.YtLoungeApi("iSponsorBlockTV") " with it present)? (y/n) "
pairing_code = input( )
"Enter pairing code (found in Settings - Link with TV code): " PAIRING_CODE_PROMPT = "Enter pairing code (found in Settings - Link with TV code): "
) ADD_MORE_DEVICES_PROMPT = "Paired with {num_devices} Device(s). Add more? (y/n) "
pairing_code = int( CHANGE_API_KEY_PROMPT = "API key already specified. Change it? (y/n) "
pairing_code.replace("-", "").replace(" ", "") ADD_API_KEY_PROMPT = "API key only needed for the channel whitelist function. Add it? (y/n) "
) # remove dashes and spaces ENTER_API_KEY_PROMPT = "Enter your API key: "
print("Pairing...") CHANGE_SKIP_CATEGORIES_PROMPT = "Skip categories already specified. Change them? (y/n) "
paired = await lounge_controller.pair(pairing_code) ENTER_SKIP_CATEGORIES_PROMPT = (
if not paired: "Enter skip categories (space or comma sepparated) Options: [sponsor,"
print("Failed to pair device") " selfpromo, exclusive_access, interaction, poi_highlight, intro, outro,"
return " preview, filler, music_offtopic]:\n"
device = { )
"screen_id": lounge_controller.auth.screen_id, WHITELIST_CHANNELS_PROMPT = "Do you want to whitelist any channels from being ad-blocked? (y/n) "
"name": lounge_controller.screen_name, SEARCH_CHANNEL_PROMPT = 'Enter a channel name or "/exit" to exit: '
} SELECT_CHANNEL_PROMPT = "Select one option of the above [0-6]: "
print(f"Paired device: {device['name']}") ENTER_CHANNEL_ID_PROMPT = "Enter a channel ID: "
return device ENTER_CUSTOM_CHANNEL_NAME_PROMPT = "Enter the channel name: "
except Exception as e: REPORT_SKIPPED_SEGMENTS_PROMPT = (
print(f"Failed to pair device: {e}") "Do you want to report skipped segments to sponsorblock. Only the segment"
return " UUID will be sent? (y/n) "
)
MUTE_ADS_PROMPT = "Do you want to mute native YouTube ads automatically? (y/n) "
def main(config, debug: bool) -> None: SKIP_ADS_PROMPT = "Do you want to skip native YouTube ads automatically? (y/n) "
print("Welcome to the iSponsorBlockTV cli setup wizard")
loop = asyncio.get_event_loop_policy().get_event_loop()
if debug: def get_yn_input(prompt):
loop.set_debug(True) while choice := input(prompt):
asyncio.set_event_loop(loop) if choice.lower() in ["y", "n"]:
if hasattr(config, "atvs"): return choice.lower()
print( print("Invalid input. Please enter 'y' or 'n'.")
"The atvs config option is deprecated and has stopped working. Please read"
" this for more information on how to upgrade to V2:" async def pair_device():
" \nhttps://github.com/dmunozv04/iSponsorBlockTV/wiki/Migrate-from-V1-to-V2" try:
) lounge_controller = ytlounge.YtLoungeApi("iSponsorBlockTV")
if ( pairing_code = input(PAIRING_CODE_PROMPT)
input( pairing_code = int(
"Do you want to remove the legacy 'atvs' entry (the app won't start" pairing_code.replace("-", "").replace(" ", "")
" with it present)? (y/n) " ) # remove dashes and spaces
) print("Pairing...")
== "y" paired = await lounge_controller.pair(pairing_code)
): if not paired:
del config["atvs"] print("Failed to pair device")
devices = config.devices return
while not input(f"Paired with {len(devices)} Device(s). Add more? (y/n) ") == "n": device = {
task = loop.create_task(pair_device()) "screen_id": lounge_controller.auth.screen_id,
loop.run_until_complete(task) "name": lounge_controller.screen_name,
device = task.result() }
if device: print(f"Paired device: {device['name']}")
devices.append(device) return device
config.devices = devices except Exception as e:
print(f"Failed to pair device: {e}")
apikey = config.apikey return
if apikey:
if input("API key already specified. Change it? (y/n) ") == "y":
apikey = input("Enter your API key: ") def main(config, debug: bool) -> None:
else: print("Welcome to the iSponsorBlockTV cli setup wizard")
if ( loop = asyncio.get_event_loop_policy().get_event_loop()
input( if debug:
"API key only needed for the channel whitelist function. Add it? (y/n) " loop.set_debug(True)
) asyncio.set_event_loop(loop)
== "y" if hasattr(config, "atvs"):
): print(
print( "The atvs config option is deprecated and has stopped working. Please read"
"Get youtube apikey here:" " this for more information on how to upgrade to V2:"
" https://developers.google.com/youtube/registering_an_application" " \nhttps://github.com/dmunozv04/iSponsorBlockTV/wiki/Migrate-from-V1-to-V2"
) )
apikey = input("Enter your API key: ") choice = get_yn_input(ATVS_REMOVAL_PROMPT)
config.apikey = apikey if choice == "y":
del config["atvs"]
skip_categories = config.skip_categories
if skip_categories: devices = config.devices
if input("Skip categories already specified. Change them? (y/n) ") == "y": choice = get_yn_input(ADD_MORE_DEVICES_PROMPT.format(num_devices=len(devices)))
categories = input( while choice == "y":
"Enter skip categories (space or comma sepparated) Options: [sponsor" task = loop.create_task(pair_device())
" selfpromo exclusive_access interaction poi_highlight intro outro" loop.run_until_complete(task)
" preview filler music_offtopic]:\n" device = task.result()
) if device:
skip_categories = categories.replace(",", " ").split(" ") devices.append(device)
skip_categories = [ choice = get_yn_input(ADD_MORE_DEVICES_PROMPT.format(num_devices=len(devices)))
x for x in skip_categories if x != "" config.devices = devices
] # Remove empty strings
else: apikey = config.apikey
categories = input( if apikey:
"Enter skip categories (space or comma sepparated) Options: [sponsor," choice = get_yn_input(CHANGE_API_KEY_PROMPT)
" selfpromo, exclusive_access, interaction, poi_highlight, intro, outro," if choice == "y":
" preview, filler, music_offtopic:\n" apikey = input(ENTER_API_KEY_PROMPT)
) else:
skip_categories = categories.replace(",", " ").split(" ") choice = get_yn_input(ADD_API_KEY_PROMPT)
skip_categories = [ if choice == "y":
x for x in skip_categories if x != "" print(
] # Remove empty strings "Get youtube apikey here:"
config.skip_categories = skip_categories " https://developers.google.com/youtube/registering_an_application"
)
channel_whitelist = config.channel_whitelist apikey = input(ENTER_API_KEY_PROMPT)
if ( config.apikey = apikey
input("Do you want to whitelist any channels from being ad-blocked? (y/n) ")
== "y" skip_categories = config.skip_categories
): if skip_categories:
if not apikey: choice = get_yn_input(CHANGE_SKIP_CATEGORIES_PROMPT)
print( if choice == "y":
"WARNING: You need to specify an API key to use this function," categories = input(ENTER_SKIP_CATEGORIES_PROMPT)
" otherwise the program will fail to start.\nYou can add one by" skip_categories = categories.replace(",", " ").split(" ")
" re-running this setup wizard." skip_categories = [
) x for x in skip_categories if x != ""
web_session = aiohttp.ClientSession() ] # Remove empty strings
api_helper = api_helpers.ApiHelper(config, web_session) else:
while True: categories = input(ENTER_SKIP_CATEGORIES_PROMPT)
channel_info = {} skip_categories = categories.replace(",", " ").split(" ")
channel = input('Enter a channel name or "/exit" to exit: ') skip_categories = [
if channel == "/exit": x for x in skip_categories if x != ""
break ] # Remove empty strings
config.skip_categories = skip_categories
task = loop.create_task(
api_helper.search_channels(channel, apikey, web_session) channel_whitelist = config.channel_whitelist
) choice = get_yn_input(WHITELIST_CHANNELS_PROMPT)
loop.run_until_complete(task) if choice == "y":
results = task.result() if not apikey:
if len(results) == 0: print(
print("No channels found") "WARNING: You need to specify an API key to use this function,"
continue " otherwise the program will fail to start.\nYou can add one by"
" re-running this setup wizard."
for i, item in enumerate(results): )
print(f"{i}: {item[1]} - Subs: {item[2]}") web_session = aiohttp.ClientSession()
print("5: Enter a custom channel ID") api_helper = api_helpers.ApiHelper(config, web_session)
print("6: Go back") while True:
channel_info = {}
choice = -1 channel = input(SEARCH_CHANNEL_PROMPT)
choice = input("Select one option of the above [0-6]: ") if channel == "/exit":
while choice not in [str(x) for x in range(7)]: break
print("Invalid choice")
choice = input("Select one option of the above [0-6]: ") task = loop.create_task(
api_helper.search_channels(channel, apikey, web_session)
if choice == "5": )
channel_info["id"] = input("Enter a channel ID: ") loop.run_until_complete(task)
channel_info["name"] = input("Enter the channel name: ") results = task.result()
channel_whitelist.append(channel_info) if len(results) == 0:
continue print("No channels found")
if choice == "6": continue
continue
for i, item in enumerate(results):
channel_info["id"] = results[int(choice)][0] print(f"{i}: {item[1]} - Subs: {item[2]}")
channel_info["name"] = results[int(choice)][1] print("5: Enter a custom channel ID")
channel_whitelist.append(channel_info) print("6: Go back")
# Close web session asynchronously
loop.run_until_complete(web_session.close()) while choice := input(SELECT_CHANNEL_PROMPT):
if choice in [str(x) for x in range(7)]:
config.channel_whitelist = channel_whitelist break
print("Invalid choice")
config.skip_count_tracking = (
not input( if choice == "5":
"Do you want to report skipped segments to sponsorblock. Only the segment" channel_info["id"] = input(ENTER_CHANNEL_ID_PROMPT)
" UUID will be sent? (y/n) " channel_info["name"] = input(ENTER_CUSTOM_CHANNEL_NAME_PROMPT)
) channel_whitelist.append(channel_info)
== "n" continue
) if choice == "6":
print("Config finished") continue
config.save()
channel_info["id"] = results[int(choice)][0]
channel_info["name"] = results[int(choice)][1]
channel_whitelist.append(channel_info)
# Close web session asynchronously
loop.run_until_complete(web_session.close())
config.channel_whitelist = channel_whitelist
choice = get_yn_input(REPORT_SKIPPED_SEGMENTS_PROMPT)
config.skip_count_tracking = choice == "y"
choice = get_yn_input(MUTE_ADS_PROMPT)
config.mute_ads = choice == "y"
choice = get_yn_input(SKIP_ADS_PROMPT)
config.skip_ads = choice == "y"
print("Config finished")
config.save()