🎨 autopep8

This commit is contained in:
2021-04-11 03:21:26 +03:00
parent 293bc42b82
commit 22ceca360c
3 changed files with 75 additions and 67 deletions

View File

@@ -34,6 +34,7 @@ https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""".format(os.path.abspath(os.path.join(os.path.dirname(__file__), """.format(os.path.abspath(os.path.join(os.path.dirname(__file__),
CLIENT_SECRETS_FILE))) CLIENT_SECRETS_FILE)))
def retrieve_youtube_subscriptions(): def retrieve_youtube_subscriptions():
# In order to retrieve the YouTube subscriptions for the current user, # In order to retrieve the YouTube subscriptions for the current user,
# the user needs to authenticate and authorize access to their YouTube # the user needs to authenticate and authorize access to their YouTube
@@ -45,14 +46,16 @@ def retrieve_youtube_subscriptions():
all_channels = [] all_channels = []
next_page_token = '' next_page_token = ''
subscriptions_response = youtube_subscriptions(youtube_authorization, next_page_token) subscriptions_response = youtube_subscriptions(
youtube_authorization, next_page_token)
total_results = subscriptions_response['pageInfo']['totalResults'] total_results = subscriptions_response['pageInfo']['totalResults']
results_per_page = subscriptions_response['pageInfo']['resultsPerPage'] results_per_page = subscriptions_response['pageInfo']['resultsPerPage']
total_iterations = math.ceil(total_results / results_per_page) total_iterations = math.ceil(total_results / results_per_page)
for _ in track(range(total_iterations), description='Fetching subscriptions'): for _ in track(range(total_iterations), description='Fetching subscriptions'):
# retrieve the YouTube subscriptions for the authorized user # retrieve the YouTube subscriptions for the authorized user
subscriptions_response = youtube_subscriptions(youtube_authorization, next_page_token) subscriptions_response = youtube_subscriptions(
youtube_authorization, next_page_token)
next_page_token = get_next_page(subscriptions_response) next_page_token = get_next_page(subscriptions_response)
# extract the required subscription information # extract the required subscription information
channels = parse_youtube_subscriptions(subscriptions_response) channels = parse_youtube_subscriptions(subscriptions_response)
@@ -62,7 +65,8 @@ def retrieve_youtube_subscriptions():
return all_channels return all_channels
except HttpError as err: except HttpError as err:
print("An HTTP error {} occurred:\n{}".format(err.resp.status, err.content)) print("An HTTP error {} occurred:\n{}".format(
err.resp.status, err.content))
def get_authenticated_service(): def get_authenticated_service():
@@ -92,8 +96,6 @@ def get_authenticated_service():
http=credentials.authorize(httplib2.Http())) http=credentials.authorize(httplib2.Http()))
# Call youtube.subscriptions.list method
# to list the channels subscribed to.
def youtube_subscriptions(youtube, next_page_token): def youtube_subscriptions(youtube, next_page_token):
subscriptions_response = youtube.subscriptions().list( subscriptions_response = youtube.subscriptions().list(
part='snippet', part='snippet',
@@ -120,8 +122,6 @@ def parse_youtube_subscriptions(subscriptions_response):
# Add each result to the appropriate list # Add each result to the appropriate list
for subscriptions_result in subscriptions_response.get("items", []): for subscriptions_result in subscriptions_response.get("items", []):
if subscriptions_result["snippet"]["resourceId"]["kind"] == "youtube#channel": if subscriptions_result["snippet"]["resourceId"]["kind"] == "youtube#channel":
#channels.append("{} ({})".format(subscriptions_result["snippet"]["title"],
# subscriptions_result["snippet"]["resourceId"]["channelId"]))
channels.append({ channels.append({
'title': subscriptions_result["snippet"]["title"], 'title': subscriptions_result["snippet"]["title"],
'id': subscriptions_result["snippet"]["resourceId"]["channelId"] 'id': subscriptions_result["snippet"]["resourceId"]["channelId"]

115
main.py
View File

@@ -10,33 +10,35 @@ from get_channels import retrieve_youtube_subscriptions
from print_logo import print_logo from print_logo import print_logo
if platform.system() == 'Windows': if platform.system() == 'Windows':
import msvcrt import msvcrt
def uni_getch():
char = str(msvcrt.getch()) def uni_getch():
if char == "b'y'": char = str(msvcrt.getch())
return True if char == "b'y'":
elif char == "b'n'": return True
return False elif char == "b'n'":
else: return False
return None else:
return None
else: else:
from getch import getch from getch import getch
def uni_getch():
char = getch() def uni_getch():
if char == "y": char = getch()
return True if char == "y":
elif char == "n": return True
return False elif char == "n":
else: return False
return None else:
return None
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', action='store', type=str, parser.add_argument('-i', '--input', action='store', type=str,
help='Path to json file generated by previously running this program.') help='Path to json file generated by previously running this program.')
parser.add_argument('-o', '--output', action='store', type=str, parser.add_argument('-o', '--output', action='store', type=str,
help='Output folder.') help='Output folder.')
parser.add_argument('-a', '--all', action='store_true', parser.add_argument('-a', '--all', action='store_true',
help='Download all subscriptions.') help='Download all subscriptions.')
args = parser.parse_args() args = parser.parse_args()
@@ -46,45 +48,50 @@ download_all = args.all
c = Console() c = Console()
ydl_opts = { ydl_opts = {
'format': 'best' 'format': 'best'
} }
print_logo() print_logo()
if json_input: if json_input:
f = open(json_input, "r", encoding='utf-8') f = open(json_input, "r", encoding='utf-8')
all_channels = json.loads(f.read()) all_channels = json.loads(f.read())
f.close() f.close()
else: else:
all_channels = retrieve_youtube_subscriptions() all_channels = retrieve_youtube_subscriptions()
curr_channel = 0 curr_channel = 0
c.print(f'You will be prompted if you want to download a channel for each of your subscriptions. (total {len(all_channels)})', style='bold') c.print(
for ch in all_channels: f'You will be prompted if you want to download a channel for each of your subscriptions. (total {len(all_channels)})', style='bold')
if download_all: for ch in all_channels:
ch['download'] = True if download_all:
else: ch['download'] = True
curr_channel += 1 else:
c.print(f'[dim][{curr_channel}/{len(all_channels)}]:[/dim] {ch["title"]} [cyan]\[y/n]') curr_channel += 1
while True: c.print(
key = uni_getch() f'[dim][{curr_channel}/{len(all_channels)}]:[/dim] {ch["title"]} [cyan]\[y/n]')
if key == True: while True:
ch['download'] = True key = uni_getch()
break if key == True:
elif key == False: ch['download'] = True
ch['download'] = False break
break elif key == False:
else: ch['download'] = False
c.print('Press "y" or "n"', style='yellow') break
else:
c.print('Press "y" or "n"', style='yellow')
c.print('All done! 🎉') c.print('All done! 🎉')
c.print('Saving to download_list.json...', style='italic') c.print('Saving to download_list.json...', style='italic')
f = open("download_list.json", "w", encoding='utf-8') f = open("download_list.json", "w", encoding='utf-8')
f.write(json.dumps(all_channels)) f.write(json.dumps(all_channels))
f.close() f.close()
for ch in all_channels: for ch in all_channels:
if ch['download']: if ch['download']:
ydl_opts['outtmpl'] = '{}/{}/%(title)s.%(ext)s'.format(output_dir, ch['title']) ydl_opts['outtmpl'] = '{}/{}/%(title)s.%(ext)s'.format(
with youtube_dl.YoutubeDL(ydl_opts) as ydl: output_dir, ch['title'])
Path(os.path.join(output_dir, ch['title'])).mkdir(parents=True, exist_ok=True) with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download(['https://www.youtube.com/channel/{}'.format(ch["id"])]) Path(os.path.join(output_dir, ch['title'])).mkdir(
parents=True, exist_ok=True)
ydl.download(
['https://www.youtube.com/channel/{}'.format(ch["id"])])

View File

@@ -1,8 +1,9 @@
from rich.console import Console from rich.console import Console
c = Console() c = Console()
def print_logo(): def print_logo():
c.print("""\ c.print("""\
__ ______ __ __________ ______ ______ __________ __ __ ______ __ __________ ______ ______ __________ __
\ \/ / __ \/ / / /_ __/ / / / __ )/ ____/ / ____/ __ \/ / \ \/ / __ \/ / / /_ __/ / / / __ )/ ____/ / ____/ __ \/ /
\ / / / / / / / / / / / / / __ / __/______/ / / / / / / \ / / / / / / / / / / / / / __ / __/______/ / / / / / /