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