import sys
import urllib
import datetime
import hashlib
import base64

OOYALA_TOKEN_URL = 'http://player.ooyala.com/sas/embed_token/%s/%s?api_key=%s&expires=%s&signature=%s'


def generate_player_token(partner_code, api_key, api_secret_key, video_code, expiration_time):
    http_method = "GET"
    slug = "/sas/embed_token/"

    request_path = slug+partner_code+"/"+video_code

    # Set the expiration date
    expiry = (datetime.datetime.now() + datetime.timedelta(seconds=expiration_time)).strftime('%s')

    # Request string with parameters
    request_string = api_secret_key + http_method + request_path + api_key + expiry

    # Generate a SHA-256 digest in base64 for request string
    m = hashlib.sha256()
    m.update(request_string)
    sha = m.digest()
    res_base = base64.b64encode(sha)

    # truncate string to 43 characters
    res_base_truncated = res_base[0:43]

    # remove any trailing = signs
    res_base_clean = res_base_truncated.rstrip('=')

    # URL encode the signature with quote(string[, safe])
    signature_for_query = urllib.quote(res_base_clean, '')

    return OOYALA_TOKEN_URL % (partner_code, video_code, api_key, expiry, signature_for_query)

@@ -64,16 +64,117 @@
 base64%0A%0A
+%0Adef generate_player_token(partner_code, api_key, api_secret_key, video_code, expiration_time):%0A%0A    
 OOYALA_T
@@ -230,13 +230,13 @@
 ken/
-%25s/%25s
+%7B%7D/%7B%7D
 ?api
@@ -240,18 +240,18 @@
 api_key=
-%25s
+%7B%7D
 &expires
@@ -251,18 +251,18 @@
 expires=
-%25s
+%7B%7D
 &signatu
@@ -268,189 +268,206 @@
 ure=
-%25s'%0A%0A%0Adef generate_player_token(partner_code, api_key, api_secret_key, video_code, expiration_time):%0A    http_method = %22GET%22%0A    slug = %22/sas/embed_token/%22%0A%0A    request_path = slug+
+%7B%7D'%0A    expiry = _expiration_timestamp_from_delta(expiration_time)%0A    signature = _generate_signature(partner_code, api_key, api_secret_key, video_code, expiry)%0A%0A    return OOYALA_TOKEN_URL.format(
 part
@@ -478,13 +478,10 @@
 code
-+%22/%22+
+, 
 vide
@@ -490,52 +490,97 @@
 code
-%0A%0A    # Set the expiration date%0A    expiry =
+, api_key, expiry, signature)%0A%0A%0Adef _expiration_timestamp_from_delta(seconds):%0A    return
  (da
@@ -630,31 +630,23 @@
 seconds=
-expiration_time
+seconds
 )).strft
@@ -660,44 +660,243 @@
 ')%0A%0A
-    # Request string with parameters
+%0Adef _generate_signature(partner_code, api_key, api_secret_key, video_code, expiry):%0A    http_method = %22GET%22%0A    slug = %22/sas/embed_token/%22%0A%0A    # Request string with parameters%0A    request_path = slug + partner_code + %22/%22 + video_code
 %0A   
@@ -1384,29 +1384,14 @@
     
-signature_for_query =
+return
  url
@@ -1424,100 +1424,4 @@
 '')%0A
-%0A    return OOYALA_TOKEN_URL %25 (partner_code, video_code, api_key, expiry, signature_for_query)%0A

Extract sub-functions from generate_player_token