playlists.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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. existing_playlist_title = item.get("snippet", {}).get("title")
  10. if existing_playlist_title.encode("utf8") == title.encode("utf-8"):
  11. return item.get("id")
  12. request = playlists.list_next(request, results)
  13. def create_playlist(youtube, title, privacy):
  14. """Create a playlist by title and return its ID"""
  15. debug("Creating playlist: {0}".format(title))
  16. response = youtube.playlists().insert(part="snippet,status", body={
  17. "snippet": {
  18. "title": title,
  19. },
  20. "status": {
  21. "privacyStatus": privacy,
  22. }
  23. }).execute()
  24. return response.get("id")
  25. def add_video_to_existing_playlist(youtube, playlist_id, video_id):
  26. """Add video to playlist (by identifier) and return the playlist ID."""
  27. debug("Adding video to playlist: {0}".format(playlist_id))
  28. return youtube.playlistItems().insert(part="snippet", body={
  29. "snippet": {
  30. "playlistId": playlist_id,
  31. "resourceId": {
  32. "kind": "youtube#video",
  33. "videoId": video_id,
  34. }
  35. }
  36. }).execute()
  37. def add_video_to_playlist(youtube, video_id, title, privacy="public"):
  38. """Add video to playlist (by title) and return the full response."""
  39. playlist_id = get_playlist(youtube, title) or \
  40. create_playlist(youtube, title, privacy)
  41. if playlist_id:
  42. return add_video_to_existing_playlist(youtube, playlist_id, video_id)
  43. else:
  44. debug("Error adding video to playlist")