playlists.py 1.9 KB

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