Browse Source

minor refactor

Arnau Sanchez 9 years ago
parent
commit
66f057f1bf
3 changed files with 26 additions and 26 deletions
  1. 16 19
      youtube_upload/main.py
  2. 9 6
      youtube_upload/playlists.py
  3. 1 1
      youtube_upload/upload_video.py

+ 16 - 19
youtube_upload/main.py

@@ -95,7 +95,7 @@ def upload_youtube_video(youtube, options, video_path, total_videos, index):
     title = u(options.title)
     description = u(options.description or "").decode("string-escape")
     tags = [u(s.strip()) for s in (options.tags or "").split(",")]
-    ns = dict(title=u(title), n=index+1, total=total_videos)
+    ns = dict(title=title, n=index+1, total=total_videos)
     title_template = u(options.title_template)
     complete_title = (title_template.format(**ns) if total_videos > 1 else title)
     progress = get_progress_info()
@@ -125,14 +125,8 @@ def upload_youtube_video(youtube, options, video_path, total_videos, index):
         progress.finish()
     return video_id
 
-def run_main(parser, options, args, output=sys.stdout):
-    """Run the main scripts from the parsed options/args."""
-    required_options = ["title"]
-    missing = [opt for opt in required_options if not getattr(options, opt)]
-    if missing:
-        parser.print_usage()
-        msg = "Some required option are missing: {0}".format(", ".join(missing))
-        raise OptionsMissing(msg)
+def get_youtube_handler(options):
+    """Return the API Youtube object."""
     home = os.path.expanduser("~")
     default_client_secrets = lib.get_first_existing_filename(
         [sys.prefix, os.path.join(sys.prefix, "local")],
@@ -145,9 +139,19 @@ def run_main(parser, options, args, output=sys.stdout):
     debug("Using credentials file: {0}".format(credentials))
     get_code_callback = (auth.browser.get_code 
         if options.auth_browser else auth.console.get_code)
-    youtube = auth.get_resource(client_secrets, credentials,
+    return auth.get_resource(client_secrets, credentials,
         get_code_callback=get_code_callback)
 
+def run_main(parser, options, args, output=sys.stdout):
+    """Run the main scripts from the parsed options/args."""
+    required_options = ["title"]
+    missing = [opt for opt in required_options if not getattr(options, opt)]
+    if missing:
+        parser.print_usage()
+        msg = "Some required option are missing: {0}".format(", ".join(missing))
+        raise OptionsMissing(msg)
+    youtube = get_youtube_handler(options)
+
     if youtube:
         for index, video_path in enumerate(args):
             video_id = upload_youtube_video(youtube, options, video_path, len(args), index)
@@ -156,16 +160,9 @@ def run_main(parser, options, args, output=sys.stdout):
 
             if options.thumb:
                 youtube.thumbnails().set(videoId=video_id, media_body=options.thumb).execute()
-
             if options.playlist:
-                response = playlists.add_video_to_playlist(youtube, video_id, 
+                playlists.add_video_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")
@@ -194,7 +191,7 @@ def main(arguments):
     parser.add_option('', '--thumbnail', dest='thumb', type="string",
         help='Video thumbnail')
     parser.add_option('', '--playlist', dest='playlist', type="string",
-        help='Playlist title (will create if necessary)')
+        help='Playlist title (if it does not exist, it will be created)')
     parser.add_option('', '--title-template', dest='title_template',
         type="string", default="{title} [{n}/{total}]", metavar="STRING",
         help='Template for multiple videos (default: {title} [{n}/{total}])')

+ 9 - 6
youtube_upload/playlists.py

@@ -3,12 +3,12 @@ from lib import debug
 def get_playlist(youtube, title):
     """Return users's playlist ID by title (None if not found)"""
     playlists = youtube.playlists()
-    request = playlists.list(mine=True, part='id,snippet')
+    request = playlists.list(mine=True, part="id,snippet")
     while request:
         results = request.execute()
-        for item in results['items']:
-            if item.get('snippet', {}).get('title') == title:
-                return item.get('id')
+        for item in results["items"]:
+            if item.get("snippet", {}).get("title") == title:
+                return item.get("id")
         request = playlists.list_next(request, results)
 
 def create_playlist(youtube, title, privacy):
@@ -22,11 +22,12 @@ def create_playlist(youtube, title, privacy):
             "privacyStatus": privacy,
         }
     }).execute()
-    return response.get('id')
+    return response.get("id")
 
 def add_video_to_existing_playlist(youtube, playlist_id, video_id):
     """Add video to playlist (by identifier) and return the playlist ID."""
-    return youtube.playlistItems().insert(part='snippet', body={
+    debug("Adding video to playlist: {0}".format(playlist_id))
+    return youtube.playlistItems().insert(part="snippet", body={
         "snippet": {
             "playlistId": playlist_id,
             "resourceId": {
@@ -42,3 +43,5 @@ def add_video_to_playlist(youtube, video_id, title, privacy="public"):
         create_playlist(youtube, title, privacy)
     if playlist_id:
         return add_video_to_existing_playlist(youtube, playlist_id, video_id)
+    else:
+        debug("Error adding video to playlist")

+ 1 - 1
youtube_upload/upload_video.py

@@ -24,7 +24,7 @@ def _upload_to_request(request, progress_callback):
                 raise KeyError("Expected field 'id' not found in response")
         elif status and progress_callback:
             progress_callback(status.total_size, status.resumable_progress)
-        
+
 def upload(resource, path, body, chunksize=1024*1024, 
         progress_callback=None, max_retries=10):
     """Upload video to Youtube. Return video ID."""