def authenticate():
    """
        Authenticate to the server and stores the cookies into a cookiejar.
        Return the cookiejar object.
    """

    configvars = dailymotion_upload.load_variables("emci.uploader.cfg")
    cookiefile = configvars['COOKIEFILE'].rstrip()
    hiddenpageurl =  configvars['HIDDENPAGE_URL'].rstrip()
    loginpageurl = configvars['LOGIN_URL'].rstrip()
    userlogin = configvars['USER_LOGIN'].rstrip()
    userpassword = configvars['USER_PASS'].rstrip()

    if os.path.exists(cookiefile):
        print "Cookie file exists. Checking the validity of the cookie"
        print "Loading cookies ..."
        parsedCookieJarFile = cookielib.MozillaCookieJar(cookiefile)
        parsedCookieJarFile.load(cookiefile)
        print parsedCookieJarFile

        print "Trying to connect to the hidden page url", hiddenpageurl
        hiidenpageopener = urllib2.build_opener()
        resp = hiidenpageopener.open(hiddenpageurl)

        response_content = resp.read()
        print "response for the page %s is %s" % (hiddenpageurl, resp.getcode())
        print "response content is %s" % (response_content)

        if resp.getcode() == 200 and "Bonjour, " in response_content:
            print "We can fetch the hidden url page", hiddenpageurl
            print "We are authenticated."
            return parsedCookieJarFile

        elif resp.getcode() == 301 or resp.getcode() == 302 or resp.getcode() == 401:
            print "Cannot access the hidden page. Doing a new authentication below ..."
        else:
            print "We have an unhandled response code.", resp.getcode()

    print "Doing a new authentication"
    print "userlogin : %s and userpassword : %s" % (userlogin, userpassword)

    login_data = urllib.urlencode({'login_form_user' : userlogin, 'login_form_pass' : userpassword})
    print "Login data is", login_data

    login_data = "login_form_user=%s&login_form_pass=%s" % (userlogin, userpassword)
    print "Login data unforged is", login_data

    storage = StringIO()
    c = pycurl.Curl()
    c.setopt(pycurl.URL, loginpageurl)
    c.setopt(c.WRITEFUNCTION, storage.write)
    c.setopt(pycurl.COOKIEFILE, cookiefile)
    c.setopt(pycurl.COOKIEJAR, cookiefile)
    c.setopt(pycurl.POST, 1)
    c.setopt(pycurl.POSTFIELDS, login_data)
    c.perform()

    content = storage.getvalue()
    print "Login request content : ", content

    return cookielib.LWPCookieJar(cookiefile)
def main():
    """
    argparser.add_argument("--file", required=True, help="Video file to upload")
    argparser.add_argument("--title", help="Video title", default="Video Title")
    argparser.add_argument("--description", help="Video description", default="Test Description")
    argparser.add_argument("--name", default="Video file name", help="The name of the video to upload.")
    args = argparser.parse_args()

    if not os.path.exists(args.file):
        exit("Please specify a valid file using the --file= parameter.")

    #youtube = get_authenticated_service(args)
    try:
        print "Sleeping for 60 seconds to prevent launchd from disabling this task"
        print "Start : %s" % time.ctime()
        #time.sleep(60)
        print "End : %s" % time.ctime()
        initialize_upload(args)
    except HttpError, e:
        print "An HTTP error %d occurred:\n%s" % (e.resp.status, e.content)

    """

    #args = []
    #initialize_uploads(args)


    print "-------  Starting EMCI upload --------"

    print "Moving to the folder where the python script is located"
    abspath = os.path.abspath(__file__)
    dname = os.path.dirname(abspath)
    print "Changing directory to", dname
    os.chdir(dname)

    validextensions = [".mp4", ".mov"]
    configvars = dailymotion_upload.load_variables("emci.uploader.cfg")

    lockfilename = configvars['lockfilename'].rstrip()
    sourcepath = configvars['sourcepath'].rstrip()
    uploadurl = configvars['UPLOAD_URL'].rstrip()
    uploadprocessurl = configvars['UPLOAD_PROCESS_URL'].rstrip()
    cookiefile = configvars['COOKIEFILE'].rstrip()

    # prevent double upload with a lock file
    dailymotion_upload.check_lock_file(lockfilename)

    # pick the first video and upload it
    print "Processing the source path" , sourcepath
    nextfiletoprocess = ""
    for name in os.listdir(sourcepath):
        (base, ext) = os.path.splitext(name)
        if ext in validextensions:
            print " === Got the one to process : ", os.path.join(sourcepath, name)
            nextfiletoprocess_name = name
            nextfiletoprocess_path = os.path.join(sourcepath, name)

            print "Break out of the loop"
            break

    # Got our file, then upload it
    nextfiletoprocess_title = "%s auto uploaded" % nextfiletoprocess_name
    nextfiletoprocess_description = "%s auto described. A real description must go here." % nextfiletoprocess_name

    # Make sure we are authenticated.
    authenticate()

    print "Uploading video ", nextfiletoprocess_path


#x    result = upload(uploadurl, nextfiletoprocess_path, cookiefile)

    print "Here is the result of the upload : ", result

    resultjson = json.loads(result)

    if resultjson.get('NewFileName'):
        NEW_FILE_UPLOAD_NAME = resultjson.get('NewFileName')
        print "New upload file name ", NEW_FILE_UPLOAD_NAME
        print "Done. Video uri is", NEW_FILE_UPLOAD_NAME

        # Set the video name and description in the page
        print "Set the video name and description ..."
        print "Setting the title of the video %s to %s" % (NEW_FILE_UPLOAD_NAME, nextfiletoprocess_title)
        setfileresult = set_name_and_descr(uploadprocessurl, NEW_FILE_UPLOAD_NAME, nextfiletoprocess_title, nextfiletoprocess_description, cookiefile)
        print "Setting file result is ", setfileresult

        if "Votre compte ne vous permet pas de voir cette page" not in setfileresult :
            print "Upload and metadata set was successfull. Status code value was %s" % (setfileresult)
            # move the file to the archive folder
            destinationpath = configvars['destination'].rstrip()
            dst = os.path.join(destinationpath, nextfiletoprocess_name)
            print "Moving video file from %s to %s" % (nextfiletoprocess_path, dst)
            os.rename(nextfiletoprocess_path, dst)

        else:
            print "Upload failed. File will not be moved to the archive so we can process it next time."
            print "Status code was %s" % (response.status_code)

    else:
        print "There is no NewFileName key in the json file", result
        print "Aborting ..."
        exit(-1)

    # remove the lock file
    dailymotion_upload.removelockfile(lockfilename)

    print "-------  EMCI upload ended --------"