playlists.py 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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. return youtube.playlistItems().insert(part='snippet', body={
  27. "snippet": {
  28. "playlistId": playlist_id,
  29. "resourceId": {
  30. "kind": "youtube#video",
  31. "videoId": video_id,
  32. }
  33. }
  34. }).execute()
  35. def add_video_to_playlist(youtube, video_id, title, privacy="public"):
  36. """Add video to playlist (by title) and return the full response."""
  37. playlist_id = get_playlist(youtube, title) or \
  38. create_playlist(youtube, title, privacy)
  39. if playlist_id:
  40. return add_video_to_existing_playlist(youtube, playlist_id, video_id)