Change order of arguments
This commit is contained in:
parent
15f332d318
commit
5c32daf593
@ -10,32 +10,28 @@ import re
|
|||||||
|
|
||||||
from googleapiclient.discovery import build
|
from googleapiclient.discovery import build
|
||||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||||
import googleapiclient.errors
|
|
||||||
|
|
||||||
scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
|
scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
|
||||||
|
|
||||||
channels = {
|
channels = {
|
||||||
"breakbeat_sesiones":"PLZFfy80_qguYVqbpQlX-aHdiYHTwc6-wW",
|
"breakbeat_sesiones": "PLZFfy80_qguYVqbpQlX-aHdiYHTwc6-wW",
|
||||||
"breakbeat_temas":"PLZFfy80_qguZnpBYfSFlkMdjGIfVcz7e7",
|
"breakbeat_temas": "PLZFfy80_qguZnpBYfSFlkMdjGIfVcz7e7",
|
||||||
"wods": "PLZFfy80_qguYCbTDQD0GSK4zUzEjbQMQT",
|
"wods": "PLZFfy80_qguYCbTDQD0GSK4zUzEjbQMQT",
|
||||||
"rap_español": "PLZFfy80_qgub44wWWDcAykdQCJNCXo4jp",
|
"rap_español": "PLZFfy80_qgub44wWWDcAykdQCJNCXo4jp",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def get_playlist_length(youtube, playlist_id):
|
def get_playlist_length(youtube, playlist_id):
|
||||||
items = youtube.playlists().list(
|
items = youtube.playlists().list(part="snippet,contentDetails", id=playlist_id)
|
||||||
part="snippet,contentDetails",
|
|
||||||
id=playlist_id
|
|
||||||
)
|
|
||||||
playlist_info = items.execute()
|
playlist_info = items.execute()
|
||||||
|
|
||||||
return playlist_info['items'][0]['contentDetails']['itemCount']
|
return playlist_info["items"][0]["contentDetails"]["itemCount"]
|
||||||
|
|
||||||
|
|
||||||
def list_songs(youtube, channel_id, stdout=False):
|
def list_songs(youtube, channel_id, stdout=False):
|
||||||
max_results = 50
|
max_results = 50
|
||||||
request = youtube.playlistItems().list(
|
request = youtube.playlistItems().list(
|
||||||
part="snippet,contentDetails",
|
part="snippet,contentDetails", maxResults=max_results, playlistId=channel_id
|
||||||
maxResults=max_results,
|
|
||||||
playlistId=channel_id
|
|
||||||
)
|
)
|
||||||
response = request.execute()
|
response = request.execute()
|
||||||
print()
|
print()
|
||||||
@ -43,9 +39,9 @@ def list_songs(youtube, channel_id, stdout=False):
|
|||||||
# Process the first page of results
|
# Process the first page of results
|
||||||
deleted = 0
|
deleted = 0
|
||||||
songs_list = []
|
songs_list = []
|
||||||
|
|
||||||
for idx, item in enumerate(response['items'], start=1):
|
for idx, item in enumerate(response["items"], start=1):
|
||||||
title = item['snippet']['title']
|
title = item["snippet"]["title"]
|
||||||
if title == "Deleted video":
|
if title == "Deleted video":
|
||||||
deleted += 1
|
deleted += 1
|
||||||
continue
|
continue
|
||||||
@ -53,36 +49,43 @@ def list_songs(youtube, channel_id, stdout=False):
|
|||||||
|
|
||||||
# Continue making requests for additional pages using pageToken
|
# Continue making requests for additional pages using pageToken
|
||||||
new_starting = 51
|
new_starting = 51
|
||||||
while 'nextPageToken' in response:
|
while "nextPageToken" in response:
|
||||||
request = youtube.playlistItems().list(
|
request = youtube.playlistItems().list(
|
||||||
part='snippet',
|
part="snippet",
|
||||||
playlistId=channel_id,
|
playlistId=channel_id,
|
||||||
maxResults=max_results,
|
maxResults=max_results,
|
||||||
pageToken=response['nextPageToken']
|
pageToken=response["nextPageToken"],
|
||||||
)
|
)
|
||||||
response = request.execute()
|
response = request.execute()
|
||||||
|
|
||||||
# Process the results for the additional pages
|
# Process the results for the additional pages
|
||||||
for idx, item in enumerate(response['items'], start=new_starting):
|
for idx, item in enumerate(response["items"], start=new_starting):
|
||||||
title = item['snippet']['title']
|
title = item["snippet"]["title"]
|
||||||
if title == "Deleted video":
|
if title == "Deleted video":
|
||||||
deleted += 1
|
deleted += 1
|
||||||
continue
|
continue
|
||||||
songs_list.append(f"{idx-deleted:02d} - {title}")
|
songs_list.append(f"{idx-deleted:02d} - {title}")
|
||||||
new_starting += 50
|
new_starting += 50
|
||||||
|
|
||||||
if stdout:
|
if stdout:
|
||||||
# Print to standard output
|
# Print to standard output
|
||||||
print("\n".join(songs_list))
|
print("\n".join(songs_list))
|
||||||
|
|
||||||
get_key_by_value = lambda dict, val: next((k for k, v in dict.items() if v == val), None)
|
# get_key_by_value = lambda dict, val: next(
|
||||||
|
# (k for k, v in dict.items() if v == val), None
|
||||||
channel_name = get_key_by_value(channels, channel_id)
|
# )
|
||||||
|
def _get_key_by_value(dict, val):
|
||||||
|
return next((k for k, v in dict.items() if v == val), None)
|
||||||
|
|
||||||
|
channel_name = _get_key_by_value(channels, channel_id)
|
||||||
|
|
||||||
# Save to file if output_file is provided
|
# Save to file if output_file is provided
|
||||||
with open(f"{channel_name} songs", 'w', encoding='utf-8') as file:
|
with open(f"{channel_name} songs", "w", encoding="utf-8") as file:
|
||||||
file.write("\n".join(songs_list))
|
file.write("\n".join(songs_list))
|
||||||
|
|
||||||
|
print("\nList created successfully!")
|
||||||
|
|
||||||
|
|
||||||
def add_song(youtube, channel_id, song):
|
def add_song(youtube, channel_id, song):
|
||||||
pos = get_playlist_length(youtube, channel_id)
|
pos = get_playlist_length(youtube, channel_id)
|
||||||
|
|
||||||
@ -92,25 +95,27 @@ def add_song(youtube, channel_id, song):
|
|||||||
"snippet": {
|
"snippet": {
|
||||||
"playlistId": channel_id,
|
"playlistId": channel_id,
|
||||||
"position": pos,
|
"position": pos,
|
||||||
"resourceId": {
|
"resourceId": {"kind": "youtube#video", "videoId": song},
|
||||||
"kind": "youtube#video",
|
|
||||||
"videoId": song
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
},
|
||||||
)
|
)
|
||||||
response = request.execute()
|
# response = request.execute()
|
||||||
|
request.execute()
|
||||||
print("\nSong added successfully!")
|
print("\nSong added successfully!")
|
||||||
|
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
parser = argparse.ArgumentParser(description="Manage YouTube playlist songs.")
|
parser = argparse.ArgumentParser(description="Manage YouTube playlist songs.")
|
||||||
parser.add_argument("-l", "--list", action="store_true", help="List songs in the playlist")
|
parser.add_argument(
|
||||||
parser.add_argument("-a", "--add", metavar="song", help="Add a song to the playlist")
|
"-l", "--list", metavar="channel_name", help="List songs in the playlist"
|
||||||
parser.add_argument("channel_name", help="Name of the playlist")
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"-a", "--add", metavar="channel_name", help="Name of the playlist"
|
||||||
|
)
|
||||||
|
parser.add_argument("song", nargs="?", help="Name of the song")
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
channel_name = args.channel_name
|
channel_name = args.add or args.list
|
||||||
channel_id = channels.get(channel_name)
|
channel_id = channels.get(channel_name)
|
||||||
|
|
||||||
if not args.list and not args.add:
|
if not args.list and not args.add:
|
||||||
@ -124,27 +129,27 @@ def main():
|
|||||||
# *DO NOT* leave this option enabled in production.
|
# *DO NOT* leave this option enabled in production.
|
||||||
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
|
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
|
||||||
|
|
||||||
api_service_name = "youtube"
|
# scopes is a global variable
|
||||||
api_version = "v3"
|
|
||||||
client_secret = "./client_secrets.json"
|
client_secret = "./client_secrets.json"
|
||||||
|
flow = InstalledAppFlow.from_client_secrets_file(client_secret, scopes)
|
||||||
flow = InstalledAppFlow.from_client_secrets_file(
|
|
||||||
client_secret, scopes)
|
|
||||||
credentials = flow.run_local_server(port=0)
|
credentials = flow.run_local_server(port=0)
|
||||||
|
|
||||||
youtube = build(
|
api_service_name = "youtube"
|
||||||
api_service_name, api_version,
|
api_version = "v3"
|
||||||
credentials=credentials)
|
youtube = build(api_service_name, api_version, credentials=credentials)
|
||||||
|
|
||||||
if args.list:
|
if args.list:
|
||||||
list_songs(youtube, channel_id, stdout=False)
|
list_songs(youtube, channel_id, stdout=False)
|
||||||
elif args.add:
|
elif args.add:
|
||||||
song = args.add
|
if not args.song:
|
||||||
# # this assumes a song is passed as in either of the following ways
|
parser.error("Please provide the name of the song with -a.")
|
||||||
# # https://youtu.be/eEnyi9L6KP4 --> split by "/"
|
song = args.song
|
||||||
# # https://youtube.com/watch?v=Ez-gizOF0Wo --> split by "="
|
# this assumes a song is passed as in either of the following ways
|
||||||
|
# https://youtu.be/eEnyi9L6KP4 --> split by "/"
|
||||||
|
# https://youtube.com/watch?v=Ez-gizOF0Wo --> split by "="
|
||||||
song = re.split(r"/|=", song)[-1]
|
song = re.split(r"/|=", song)[-1]
|
||||||
add_song(youtube, channel_id, song)
|
add_song(youtube, channel_id, song)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
main()
|
main()
|
||||||
|
Loading…
Reference in New Issue
Block a user