Esempio n. 1
0
def run_main(parser, options, args, output=sys.stdout):
    """Run the main scripts from the parsed options/args."""
    if options.get_categories:
        output.write(" ".join(Youtube.get_categories().keys()) + "\n")
        return
    elif (options.create_playlist or options.add_to_playlist or 
         options.delete_from_playlist or options.update_metadata):
        required_options = ["email"]
    else:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video file to upload")
        required_options = ["email", "title", "category"]

    missing = [opt for opt in required_options if not getattr(options, opt)]
    if missing:
        parser.print_usage()
        raise OptionsMissing("Some required option are missing: %s" % ", ".join(missing))

    if options.password is None:
        password = getpass.getpass("Password for account <%s>: " % options.email)
    elif options.password == "-":
        password = sys.stdin.readline().strip()
    else:
        password = options.password
    youtube = Youtube(DEVELOPER_KEY)
    debug("Login to Youtube API: email='%s', password='******'" %
          (options.email, "*" * len(password)))
    try:
        youtube.login(options.email, password, captcha_token=options.captcha_token,
                      captcha_response=options.captcha_response)
    except gdata.service.BadAuthentication:
        raise BadAuthentication("Authentication failed")
    except gdata.service.CaptchaRequired:
        token = youtube.service.captcha_token
        message = [
            "Captcha request: %s" % youtube.service.captcha_url,
            "Re-run the command with: --captcha-token=%s --captcha-response=CAPTCHA" % token,
        ]
        raise CaptchaRequired("\n".join(message))

    if options.create_playlist:
        title, description, private = tosize(options.create_playlist.split("|", 2), 3)
        playlist_uri = youtube.create_playlist(title, description, (private == "1"))
        debug("Playlist created: %s" % playlist_uri)
        output.write(playlist_uri+"\n")
    elif options.update_metadata:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video URL to upload")
        url = args[0]            
        updated = youtube.update_metadata(url, options.title, options.description)
        debug("Video metadata updated: %s" % url)
    elif options.add_to_playlist:
        for url in args:
            debug("Adding video (%s) to playlist: %s" % (url, options.add_to_playlist))
            video_id = get_video_id_from_url(url)
            youtube.add_video_to_playlist(video_id, options.add_to_playlist)
    elif options.delete_from_playlist:
        playlist = options.delete_from_playlist
        for url in args:
            video_id = get_video_id_from_url(url)
            debug("delete video (%s) from playlist: %s; video-id: %s" % 
              (url, playlist, video_id))
            youtube.delete_video_from_playlist(video_id, playlist)
    else:
      for index, video_path in enumerate(args):
        url = upload_video(youtube, options, video_path, len(args), index)
        output.write(url + "\n")
Esempio n. 2
0
def run_main(parser, options, args, output=sys.stdout):
    """Run the main scripts from the parsed options/args."""
    if options.get_categories:
        output.write(" ".join(Youtube.get_categories().keys()) + "\n")
        return
    elif (options.create_playlist or options.add_to_playlist
          or options.delete_from_playlist or options.update_metadata):
        required_options = ["email"]
    else:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video file to upload")
        required_options = ["email", "title", "category"]

    missing = [opt for opt in required_options if not getattr(options, opt)]
    if missing:
        parser.print_usage()
        raise OptionsMissing("Some required option are missing: %s" %
                             ", ".join(missing))

    if options.password is None:
        password = getpass.getpass("Password for account <%s>: " %
                                   options.email)
    elif options.password == "-":
        password = sys.stdin.readline().strip()
    else:
        password = options.password
    youtube = Youtube(DEVELOPER_KEY)
    debug("Login to Youtube API: email='%s', password='******'" %
          (options.email, "*" * len(password)))
    try:
        youtube.login(options.email,
                      password,
                      captcha_token=options.captcha_token,
                      captcha_response=options.captcha_response)
    except gdata.service.BadAuthentication:
        raise BadAuthentication("Authentication failed")
    except gdata.service.CaptchaRequired:
        token = youtube.service.captcha_token
        message = [
            "Captcha request: %s" % youtube.service.captcha_url,
            "Re-run the command with: --captcha-token=%s --captcha-response=CAPTCHA"
            % token,
        ]
        raise CaptchaRequired("\n".join(message))

    if options.create_playlist:
        title, description, private = tosize(
            options.create_playlist.split("|", 2), 3)
        playlist_uri = youtube.create_playlist(title, description,
                                               (private == "1"))
        debug("Playlist created: %s" % playlist_uri)
        output.write(playlist_uri + "\n")
    elif options.update_metadata:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video URL to upload")
        url = args[0]
        updated = youtube.update_metadata(url, options.title,
                                          options.description)
        debug("Video metadata updated: %s" % url)
    elif options.add_to_playlist:
        for url in args:
            debug("Adding video (%s) to playlist: %s" %
                  (url, options.add_to_playlist))
            video_id = get_video_id_from_url(url)
            youtube.add_video_to_playlist(video_id, options.add_to_playlist)
    elif options.delete_from_playlist:
        playlist = options.delete_from_playlist
        for url in args:
            video_id = get_video_id_from_url(url)
            debug("delete video (%s) from playlist: %s; video-id: %s" %
                  (url, playlist, video_id))
            youtube.delete_video_from_playlist(video_id, playlist)
    else:
        for index, video_path in enumerate(args):
            url = upload_video(youtube, options, video_path, len(args), index)
            output.write(url + "\n")
Esempio n. 3
0
def main_upload(arguments, output=sys.stdout):
    """Upload video to Youtube."""
    usage = """Usage: %prog [OPTIONS] VIDEO_PATH ...

    Upload videos to youtube."""    
    parser = optparse.OptionParser(usage, version=VERSION)

    # Required options
    parser.add_option('-m', '--email', dest='email', type="string", 
        help='Authentication user email')
    parser.add_option('-p', '--password', dest='password', type="string", 
        help='Authentication user password')
    parser.add_option('-t', '--title', dest='title', type="string", 
        help='Video(s) title')
    parser.add_option('-c', '--category', dest='category', type="string", 
        help='Video(s) category')

    # Side commands
    parser.add_option('', '--get-categories', dest='get_categories',
        action="store_true", default=False, help='Show video categories')
    parser.add_option('', '--create-playlist', dest='create_playlist', type="string", 
        default=None, metavar="TITLE|DESCRIPTION|PRIVATE (0=no, 1=yes)", 
        help='Create new playlist and add uploaded video(s) to it')

    # Optional options
    parser.add_option('-d', '--description', dest='description', type="string", 
        help='Video(s) description')
    parser.add_option('', '--keywords', dest='keywords', type="string", 
        help='Video(s) keywords (separated by commas: tag1,tag2,...)')
    parser.add_option('', '--title-template', dest='title_template', type="string",
        default="$title [$n/$total]", metavar="STRING", 
        help='Title template to use on multiple videos (default: $title [$n/$total])')
    parser.add_option('', '--private', dest='private',
        action="store_true", default=False, help='Set uploaded video(s) as private')
    parser.add_option('', '--location', dest='location', type="string", default=None,
        metavar="LAT,LON", help='Video(s) location (lat, lon). example: "43.3,5.42"')
    
    # Upload options
    parser.add_option('', '--api-upload', dest='api_upload',
        action="store_true", default=False, help="Use the API upload instead of pycurl")
    parser.add_option('', '--get-upload-form-info', dest='get_upload_form_data',
        action="store_true", default=False, help="Don't upload, get the form info (PATH, TOKEN, URL)")
        
    # Playlist options
    parser.add_option('', '--add-to-playlist', dest='add_to_playlist', type="string", default=None,
        metavar="URI", help='Add video(s) to an existing playlist')
    parser.add_option('', '--wait-processing', dest='wait_processing', action="store_true", 
        default=False, help='Wait until the video(s) has been processed')

    # Captcha options
    parser.add_option('', '--captcha-token', dest='captcha_token', type="string", 
      metavar="STRING", help='Captcha token')
    parser.add_option('', '--captcha-response', dest='captcha_response', type="string", 
      metavar="STRING", help='Captcha response')

    options, args = parser.parse_args(arguments)
    
    if options.get_categories:
        output.write(" ".join(Youtube.get_categories().keys()) + "\n")
        return
    elif options.create_playlist or options.add_to_playlist:
        required_options = ["email", "password"]
    else:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video file to upload")    
        required_options = ["email", "title", "category"]
                
    missing = [opt for opt in required_options if not getattr(options, opt)]
    if missing:
        parser.print_usage()
        raise OptionsMissing("Some required option are missing: %s" % ", ".join(missing)) 
        
    if options.password is None:
        password = getpass.getpass("Password for account <%s>: " % options.email)    
    elif options.password == "-":
        password = sys.stdin.readline().strip()
    else:
        password = options.password
    youtube = Youtube(DEVELOPER_KEY)    
    debug("Login to Youtube API: email='%s', password='******'" % 
          (options.email, "*" * len(password)))
    try:
        youtube.login(options.email, password, captcha_token=options.captcha_token,
                      captcha_response=options.captcha_response)
    except gdata.service.BadAuthentication:
        raise BadAuthentication("Wrong authentication")                      
    except gdata.service.CaptchaRequired:
        token = youtube.service.captcha_token
        message = [
            "Captcha request: %s" % youtube.service.captcha_url,
            "Re-run the command: --captcha-token=%s --captcha-response=CAPTCHA" % token,
        ]
        raise CaptchaRequired("\n".join(message))

    if options.create_playlist:
        title, description, private = tosize(options.create_playlist.split("|", 2), 3)
        playlist_uri = youtube.create_playlist(title, description, (private == "1"))
        debug("Playlist created: %s" % playlist_uri)
        output.write(playlist_uri+"\n")
        return

    if options.add_to_playlist:
        for url in args:
            debug("Adding video (%s) to playlist: %s" % (url, options.add_to_playlist))
            video_id = re.search("v=(.*)$", url).group(1)
            youtube.add_video_to_playlist(video_id, options.add_to_playlist)
        return 
    
    videos = args
    for index, video_path in enumerate(videos):
        namespace = dict(title=options.title, n=index+1, total=len(videos))
        complete_title = (string.Template(options.title_template).substitute(**namespace) 
                          if len(videos) > 1 else options.title)
        args = [video_path, complete_title, options.description, 
                options.category, options.keywords]
        kwargs = dict(private=options.private, location=parse_location(options.location))
        
        if options.get_upload_form_data:
            data = youtube.get_upload_form_data(*args, **kwargs)
            output.write("\n".join([video_path, data["token"], data["post_url"]]) + "\n")
            continue
        elif options.api_upload or not pycurl:
            if not options.api_upload:
                debug("Install pycurl to upload the video using HTTP")
            debug("Start upload using basic gdata API: %s" % video_path) 
            entry = youtube.upload_video(*args, **kwargs)
            url, video_id = get_entry_info(entry)
        else: # upload with curl
            data = youtube.get_upload_form_data(*args, **kwargs)
            entry = data["entry"]
            debug("Start upload using a HTTP post: %s" % video_path)
            http_code, headers, body = \
                post(data["post_url"], {"file": video_path}, {"token": data["token"]})
            if http_code != 302:
                raise UnsuccessHTTPResponseCode(
                    "HTTP code on upload: %d (expected 302)" % http_code)
            params = dict(s.split("=", 1) for s in headers["Location"].split("?", 1)[1].split("&"))
            if params["status"] !=  "200":
                raise UnsuccessHTTPResponseCode(
                    "HTTP status on upload link: %s (expected 200)" % params["status"])
            video_id = params["id"]
            url = "http://www.youtube.com/watch?v=%s" % video_id
        if options.wait_processing:
            wait_processing(youtube, video_id)
        output.write(url + "\n")
Esempio n. 4
0
def main_upload(arguments, output=sys.stdout):
    """Upload video to Youtube."""
    usage = """Usage: %prog [OPTIONS] VIDEO_PATH ...

    Upload videos to youtube."""
    parser = optparse.OptionParser(usage, version=VERSION)

    # Required options
    parser.add_option('-m', '--email', dest='email', type="string",
        help='Authentication user email')
    parser.add_option('-p', '--password', dest='password', type="string",
        help='Authentication user password')
    parser.add_option('-t', '--title', dest='title', type="string",
        help='Video(s) title')
    parser.add_option('-c', '--category', dest='category', type="string",
        help='Video(s) category')

    # Side commands
    parser.add_option('', '--get-categories', dest='get_categories',
        action="store_true", default=False, help='Show video categories')
    parser.add_option('', '--create-playlist', dest='create_playlist', type="string",
        default=None, metavar="TITLE|DESCRIPTION|PRIVATE (0=no, 1=yes)",
        help='Create new playlist and add uploaded video(s) to it')

    # Optional options
    parser.add_option('-d', '--description', dest='description', type="string",
        help='Video(s) description')
    parser.add_option('', '--keywords', dest='keywords', type="string",
        help='Video(s) keywords (separated by commas: tag1,tag2,...)')
    parser.add_option('', '--title-template', dest='title_template', type="string",
        default="$title [$n/$total]", metavar="STRING",
        help='Title template to use on multiple videos (default: $title [$n/$total])')
    parser.add_option('', '--private', dest='private',
        action="store_true", default=False, help='Set uploaded video(s) as private')
    parser.add_option('', '--unlisted', dest='unlisted',
        action="store_true", default=False, help='Set uploaded video(s) as unlisted')
    parser.add_option('', '--location', dest='location', type="string", default=None,
        metavar="LAT,LON", help='Video(s) location (lat, lon). example: "43.3,5.42"')

    # Upload options
    parser.add_option('', '--api-upload', dest='api_upload',
        action="store_true", default=False, help="Use the API upload instead of pycurl")
    parser.add_option('', '--get-upload-form-info', dest='get_upload_form_data',
        action="store_true", default=False, help="Don't upload, get the form info (PATH, TOKEN, URL)")

    # Playlist options
    parser.add_option('', '--add-to-playlist', dest='add_to_playlist', type="string", default=None,
        metavar="URI", help='Add video(s) to an existing playlist')
    parser.add_option('', '--wait-processing', dest='wait_processing', action="store_true",
        default=False, help='Wait until the video(s) has been processed')

    # Captcha options
    parser.add_option('', '--captcha-token', dest='captcha_token', type="string",
      metavar="STRING", help='Captcha token')
    parser.add_option('', '--captcha-response', dest='captcha_response', type="string",
      metavar="STRING", help='Captcha response')

    options, args = parser.parse_args(arguments)

    if options.get_categories:
        output.write(" ".join(Youtube.get_categories().keys()) + "\n")
        return
    elif options.create_playlist or options.add_to_playlist:
        required_options = ["email", "password"]
    else:
        if not args:
            parser.print_usage()
            raise VideoArgumentMissing("Specify a video file to upload")
        required_options = ["email", "title", "category"]

    missing = [opt for opt in required_options if not getattr(options, opt)]
    if missing:
        parser.print_usage()
        raise OptionsMissing("Some required option are missing: %s" % ", ".join(missing))

    if options.password is None:
        password = getpass.getpass("Password for account <%s>: " % options.email)
    elif options.password == "-":
        password = sys.stdin.readline().strip()
    else:
        password = options.password
    youtube = Youtube(DEVELOPER_KEY)
    debug("Login to Youtube API: email='%s', password='******'" %
          (options.email, "*" * len(password)))
    try:
        youtube.login(options.email, password, captcha_token=options.captcha_token,
                      captcha_response=options.captcha_response)
    except gdata.service.BadAuthentication:
        raise BadAuthentication("Authentication failed")
    except gdata.service.CaptchaRequired:
        token = youtube.service.captcha_token
        message = [
            "Captcha request: %s" % youtube.service.captcha_url,
            "Re-run the command with: --captcha-token=%s --captcha-response=CAPTCHA" % token,
        ]
        raise CaptchaRequired("\n".join(message))

    if options.create_playlist:
        title, description, private = tosize(options.create_playlist.split("|", 2), 3)
        playlist_uri = youtube.create_playlist(title, description, (private == "1"))
        debug("Playlist created: %s" % playlist_uri)
        output.write(playlist_uri+"\n")
        return

    if options.add_to_playlist:
        for url in args:
            debug("Adding video (%s) to playlist: %s" % (url, options.add_to_playlist))
            video_id = get_video_id_from_url(url)
            youtube.add_video_to_playlist(video_id, options.add_to_playlist)
        return

    videos = args
    for index, video_path in enumerate(videos):
        namespace = dict(title=options.title, n=index+1, total=len(videos))
        complete_title = (string.Template(options.title_template).substitute(**namespace)
                          if len(videos) > 1 else options.title)
        args = [video_path, complete_title, options.description,
                options.category, options.keywords]
        kwargs = {
          "private": options.private,
          "location": parse_location(options.location),
          "unlisted": options.unlisted,
        }

        if options.get_upload_form_data:
            data = youtube.get_upload_form_data(*args, **kwargs)
            output.write("\n".join([video_path, data["token"], data["post_url"]]) + "\n")
            continue
        elif options.api_upload or not pycurl:
            if not options.api_upload:
                debug("Install pycurl to upload the video using HTTP")
            debug("Start upload using basic gdata API: %s" % video_path)
            entry = youtube.upload_video(*args, **kwargs)
            url, video_id = get_entry_info(entry)
        else: # upload with curl
            data = youtube.get_upload_form_data(*args, **kwargs)
            entry = data["entry"]
            debug("Start upload using a HTTP post: %s" % video_path)
            http_code, headers, body = \
                post(data["post_url"], {"file": video_path}, {"token": data["token"]})
            if http_code != 302:
                raise UnsuccessfulHTTPResponseCode(
                    "HTTP code on upload: %d (expected 302)" % http_code)
            params = dict(s.split("=", 1) for s in headers["Location"].split("?", 1)[1].split("&"))
            if params["status"] !=  "200":
                raise UnsuccessfulHTTPResponseCode(
                    "HTTP status on upload link: %s (expected 200)" % params["status"])
            video_id = params["id"]
            url = "http://www.youtube.com/watch?v=%s" % video_id
        if options.wait_processing:
            wait_processing(youtube, video_id)
        output.write(url + "\n")