Fetch video info during add/remove to playlist

This commit is contained in:
Maks Snegov 2024-02-03 14:08:42 -08:00
parent acd15f49f1
commit a9f006bc84

30
main.py
View File

@ -117,9 +117,11 @@ def list_playlist(yt_api, playlist_id: str):
def add_video_to_playlist(yt_api, video_id: str, playlist_id: str,
dry_run: bool = False) -> bool:
playlist_name = get_playlist_name(playlist_id)
video_info = get_video_info(yt_api, video_id)
video_title = _truncate_title(video_info['snippet']['title'])
try:
if dry_run:
print(f"Would add video {video_id} to playlist {playlist_name}")
print(f"Would add video '{video_title}' [{video_id}] to playlist {playlist_name}")
return True
yt_api.playlistItems().insert(
part='snippet',
@ -133,29 +135,32 @@ def add_video_to_playlist(yt_api, video_id: str, playlist_id: str,
}
}
).execute()
print(f"Added video {video_id} to playlist {playlist_name}")
print(f"Added video '{video_title}' [{video_id}] to playlist {playlist_name}")
return True
except HttpError as e:
exit_on_exceeded_quota(e)
print(f"Error adding video {video_id} to playlist {playlist_name}: {e}")
print(f"Error adding video '{video_title}' [{video_id}] to playlist {playlist_name}: {e}")
return False
def remove_video_from_playlist(yt_api, plitem_id: str, playlist_id: str,
dry_run: bool = False) -> bool:
playlist_name = get_playlist_name(playlist_id)
plitem_info = get_playlistitem_info(yt_api, plitem_id)
video_title = _truncate_title(plitem_info['snippet']['title'])
video_id = plitem_info['snippet']['resourceId']['videoId']
try:
if dry_run:
print(f"Would remove playlist item {plitem_id}]"
print(f"Would remove video '{video_title}' [{video_id}]"
f" from playlist {playlist_name}")
return True
yt_api.playlistItems().delete(id=plitem_id).execute()
print(f"Removed playlist item {plitem_id}"
print(f"Removed video '{video_title}' [{video_id}]"
f" from playlist {playlist_name}")
return True
except HttpError as e:
exit_on_exceeded_quota(e)
print(f"Error removing playlist item {plitem_id}"
print(f"Error removing video '{video_title}' [{video_id}]"
f" from playlist {playlist_name}: {e}")
return False
@ -201,6 +206,19 @@ def get_video_info(youtube, video_id: str):
return None
def get_playlistitem_info(youtube, playlistitem_id: str):
try:
response = youtube.playlistItems().list(
part="snippet",
id=playlistitem_id
).execute()
return response['items'][0]
except HttpError as e:
exit_on_exceeded_quota(e)
print(f'Error getting playlist item {playlistitem_id}: {e}')
return None
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-n', '--dry-run', action='store_true',