playlists.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. from .lib import debug
  2. def get_playlist(youtube, title):
  3. """Return users's playlist ID by title (None if not found)"""
  4. playlists = youtube.playlists()
  5. request = playlists.list(mine=True, part="id,snippet")
  6. while request:
  7. results = request.execute()
  8. for item in results["items"]:
  9. if item.get("snippet", {}).get("title") == title:
  10. return item.get("id")
  11. request = playlists.list_next(request, results)
  12. def create_playlist(youtube, title, privacy):
  13. """Create a playlist by title and return its ID"""
  14. debug("Creating playlist: {0}".format(title))
  15. response = youtube.playlists().insert(part="snippet,status", body={
  16. "snippet": {
  17. "title": title,
  18. },
  19. "status": {
  20. "privacyStatus": privacy,
  21. }
  22. }).execute()
  23. return response.get("id")
  24. def add_video_to_existing_playlist(youtube, playlist_id, video_id):
  25. """Add video to playlist (by identifier) and return the playlist ID."""
  26. debug("Adding video to playlist: {0}".format(playlist_id))
  27. return youtube.playlistItems().insert(part="snippet", body={
  28. "snippet": {
  29. "playlistId": playlist_id,
  30. "resourceId": {
  31. "kind": "youtube#video",
  32. "videoId": video_id,
  33. }
  34. }
  35. }).execute()
  36. def add_video_to_playlist(youtube, video_id, title, privacy="public"):
  37. """Add video to playlist (by title) and return the full response."""
  38. playlist_id = get_playlist(youtube, title) or \
  39. create_playlist(youtube, title, privacy)
  40. if playlist_id:
  41. return add_video_to_existing_playlist(youtube, playlist_id, video_id)
  42. else:
  43. debug("Error adding video to playlist")