Browse Source

refactor playlist.py

Arnau Sanchez 9 years ago
parent
commit
c1d678cd31
2 changed files with 45 additions and 40 deletions
  1. 9 3
      youtube_upload/main.py
  2. 36 37
      youtube_upload/playlists.py

+ 9 - 3
youtube_upload/main.py

@@ -152,14 +152,20 @@ def run_main(parser, options, args, output=sys.stdout):
         for index, video_path in enumerate(args):
             video_id = upload_youtube_video(youtube, options, video_path, len(args), index)
             video_url = WATCH_VIDEO_URL.format(id=video_id)
+            debug("Video URL: {0}".format(video_url))
 
             if options.thumb:
                 youtube.thumbnails().set(videoId=video_id, media_body=options.thumb).execute()
 
             if options.playlist:
-                playlists.add_to_playlist(youtube, video_id, options)
-
-            debug("Video URL: {0}".format(video_url))
+                response = playlists.add_to_playlist(youtube, video_id, 
+                    title=options.playlist, privacy=options.privacy)
+                if response:
+                    playlist_id = response["snippet"]["playlistId"]
+                    debug("Video added to playlist: {0}".format(playlist_id))
+                else:
+                    debug("Error adding video to playlist")
+                    
             output.write(video_id + "\n")
     else:
         raise AuthenticationError("Cannot get youtube resource")

+ 36 - 37
youtube_upload/playlists.py

@@ -1,46 +1,45 @@
 from lib import debug
 
-def add_to_playlist(youtube, video_id, options):
-    # find playlist with given name
-    existing_playlist_id = None
+
+def get_playlist(youtube, title):
+    """Return users's playlist by title (None if not found)"""
     playlists = youtube.playlists()
     request = playlists.list(mine=True, part='id,snippet')
-    while request is not None:
+    while request:
         results = request.execute()
         for item in results['items']:
-            if item.get('snippet', {}).get('title') == options.playlist:
-                existing_playlist_id = item.get('id')
-
-        # stop paginating playlists on first matching playlist title
-        if existing_playlist_id is None:
-            request = playlists.list_next(request, results)
-        else:
-            break
+            if item.get('snippet', {}).get('title') == title:
+                return item.get('id')
+        request = playlists.list_next(request, results)
 
-    # create playlist, if necessary
-    if existing_playlist_id is None:
-        playlists_insert_response = youtube.playlists().insert(part="snippet,status", body={
-            "snippet": {
-                "title": options.playlist
-            },
-            "status": {
-                "privacyStatus": options.privacy
-            }
-        }).execute()
-        existing_playlist_id = playlists_insert_response.get('id', None)
+def create_playlist(youtube, title, privacy):
+    """Create a playlist by title"""
+    response = youtube.playlists().insert(part="snippet,status", body={
+        "snippet": {
+            "title": title,
+        },
+        "status": {
+            "privacyStatus": privacy,
+        }
+    }).execute()
+    return response.get('id', None)
 
-    # something has gone wrong
-    if existing_playlist_id is None:
-        debug('Error creating playlist')
-    else:
-        # add video to playlist
-        youtube.playlistItems().insert(part='snippet', body={
-            "snippet": {
-                "playlistId": existing_playlist_id,
-                "resourceId": {
-                    "kind": "youtube#video",
-                    "videoId": video_id
-                }
+def add_video_to_playlist(youtube, playlist_id, video_id):
+    """Add video to playlist (by identifier)."""
+    return youtube.playlistItems().insert(part='snippet', body={
+        "snippet": {
+            "playlistId": playlist_id,
+            "resourceId": {
+                "kind": "youtube#video",
+                "videoId": video_id
             }
-        }).execute()
-        debug("Added video to playlist '{0}'".format(options.playlist))
+        }
+    }).execute()
+    return playlist_id
+    
+def add_to_playlist(youtube, video_id, title, privacy="public"):
+    """Add video to playlist (by title)."""
+    playlist_id = get_playlist(youtube, title) or \
+        create_playlist(youtube, title, privacy)
+    if playlist_id:
+        return add_video_to_playlist(youtube, playlist_id, video_id)