예제 #1
0
def test_custom_initialization():

    KEY = '_key_'
    SECRET = '_secret_'
    SCHEME = 'http'
    HOST = 'api.host.domain'
    PORT = 8080
    API_VERSION = 'v7'
    AGENT = 'test_agent'

    jwp_client = jwplatform.Client(
        KEY, SECRET,
        scheme=SCHEME,
        host=HOST,
        port=PORT,
        version=API_VERSION,
        agent=AGENT)

    assert jwp_client._Client__key == KEY
    assert jwp_client._Client__secret == SECRET
    assert jwp_client._scheme == SCHEME
    assert jwp_client._host == HOST
    assert jwp_client._port == PORT
    assert jwp_client._api_version == API_VERSION
    assert jwp_client._agent == AGENT
    assert 'User-Agent' in jwp_client._connection.headers
    assert jwp_client._connection.headers['User-Agent'] == \
        'python-jwplatform/{}-{}'.format(jwplatform.__version__, AGENT)
예제 #2
0
def test_custom_initialization_empty_kwargs():

    KEY = 'api_key'
    SECRET = 'api_secret'
    SCHEME = None
    HOST = None
    PORT = None
    API_VERSION = None
    AGENT = None

    jwp_client = jwplatform.Client(
        KEY, SECRET,
        scheme=SCHEME,
        host=HOST,
        port=PORT,
        version=API_VERSION,
        agent=AGENT)

    assert jwp_client._Client__key == KEY
    assert jwp_client._Client__secret == SECRET
    assert jwp_client._scheme == 'https'
    assert jwp_client._host == 'api.jwplatform.com'
    assert jwp_client._port == 80
    assert jwp_client._api_version == 'v1'
    assert jwp_client._agent is None
    assert 'User-Agent' in jwp_client._connection.headers
    assert jwp_client._connection.headers['User-Agent'] == \
        'python-jwplatform/{}'.format(jwplatform.__version__)
예제 #3
0
def test_required_parameters_present():

    KEY = 'api_key'
    SECRET = 'api_secret'

    jwp_client = jwplatform.Client(KEY, SECRET)

    url, params = jwp_client._build_request('')

    assert url == 'https://api.jwplatform.com/v1'

    assert 'api_nonce' in params
    assert len(params['api_nonce']) == 9
    assert 0 <= int(params['api_nonce']) <= 999999999

    assert 'api_timestamp' in params
    assert params['api_timestamp'] <= int(time.time())

    assert 'api_key' in params
    assert params['api_key'] == KEY

    assert 'api_format' in params
    assert params['api_format'] == 'json'

    assert 'api_kit' in params
    assert params['api_kit'] == 'py-{}'.format(jwplatform.__version__)

    assert 'api_signature' in params
예제 #4
0
def test_existing_resource():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/videos/show\?.*'
                          'video_key=VideoKey.*')
    responses.add(
        responses.GET,
        url_expr,
        status=200,
        content_type='application/json',
        body='{"status": "ok", '
        '"rate_limit": {"reset": 1478929300, "limit": 50, "remaining": 47},'
        '"video": {"status": "ready", "expires_date": null, "description": null, '
        '"title": "Title", "views": 179, "tags": "", "sourceformat": null, '
        '"mediatype": "video", "upload_session_id": null, "custom": {}, '
        '"duration": "817.56", "sourceurl": null, "link": null, "author": null, '
        '"key": "VideoKey", "error": null, "date": 1464754765, '
        '"md5": "653bc15b6cba7319c2df9b5cf869b5b8", "sourcetype": "file", '
        '"size": "904237686"}}')

    jwp_client = jwplatform.Client('api_key',
                                   'api_secret',
                                   host='api.test.tst')
    resp = jwp_client.videos.show(video_key='VideoKey')

    assert resp['status'] == 'ok'
    assert 'status' in resp['video']
    assert resp['video']['key'] == 'VideoKey'
예제 #5
0
def update_custom_params(api_key,
                         api_secret,
                         video_key,
                         params=default_params):
    """
    Function which allows you to update a video's custom params. Custom params are indicated by key-values of
    "custom.<key>" = "<value>" so they must be provided as a dictionary and passed to the platform API call.
    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
    :param params: Custom params in the format of a dictionary, e.g.
        >>> params = {'year': '2017', 'category': 'comedy'}
        >>> update_custom_params('XXXXXXXX', 'XXXXXXXXXXXXXXXXX', 'dfT6JSb2', params)
    :return: None
    """
    formatted_params = {'custom.{}'.format(k): v for k, v in params.items()}

    # Setup API client
    jwplatform_client = jwplatform.Client(JWPLAYER_FC_KEY, JWPLAYER_FC_SECRET)
    logging.info("Updating Video")
    try:
        response = jwplatform_client.videos.update(video_key=video_key,
                                                   **formatted_params)
    except jwplatform.errors.JWPlatformError as e:
        logging.error("Encountered an error updating the video\n{}".format(e))
        sys.exit(e.message)
    logging.info(response)
예제 #6
0
def update_thumbnail(api_key, api_secret, video_key, position=7.0, **kwargs):
    """
    Function which updates the thumbnail for an EXISTING video utilizing position parameter.
    This function is useful for selecting a new thumbnail from with the already existing video content.
    Instead of position parameter, user may opt to utilize thumbnail_index parameter.
    Please eee documentation for further information.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
    :param position: <float> Represents seconds into the duration of a video, for thumbnail extraction.
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
    :return: <dict> Dict which represents the JSON response.
    """
    jwplatform_client = jwplatform.Client(api_key, api_secret)
    logging.info("Updating video thumbnail.")
    try:
        response = jwplatform_client.videos.thumbnails.update(
            video_key=video_key,
            position=position,  # Parameter which specifies seconds into video to extract thumbnail from.
            **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error("Encountered an error updating thumbnail.\n{}".format(e))
        sys.exit(e.message)
    return response
예제 #7
0
	def __init__(self, clientId):
		self.clientId = clientId
		api_key = r'03IfLqqB'
		api_secret = r'AK6y0bBoyEOHASfYwE5xUnWw'
		#api_key = r'avfMTzPK'
		#api_secret = r'k7HIvXAueCNF0G7I8A88Ecor'
		# Setup API client
		self.jwplatform_client = jwplatform.Client(api_key, api_secret)
예제 #8
0
def get_jwplatform_client():
    """
    Examine the settings and return an authenticated :py:class:`jwplatform.Client` instance.

    .. seealso::

        The `jwplatform module on GitHub <https://github.com/jwplayer/jwplatform-py>`_.

    """
    return jwplatform.Client(settings.JWPLATFORM_API_KEY, settings.JWPLATFORM_API_SECRET)
예제 #9
0
def test_post_parameters_in_url():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/a/b/c/d\?.*')
    responses.add(
        responses.POST, url_expr,
        status=200,
        content_type='application/json',
        body='{"status": "ok"}')

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')
    resp = jwp_client.a.b.c.d(http_method='POST', use_body=False, _post='true', _body='false')

    assert resp['status'] == 'ok'
예제 #10
0
def test_post_existing_resource():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/a/b/c/d')
    responses.add(
        responses.POST, url_expr,
        status=200,
        content_type='application/json',
        body='{"status": "ok"}')

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')
    resp = jwp_client.a.b.c.d(http_method='POST', abcde=123)

    assert resp['status'] == 'ok'
예제 #11
0
def test_long_resource():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/a/b/c/d/f/e\?.*'
                          'abcde=.*')
    responses.add(
        responses.GET, url_expr,
        status=200,
        content_type='application/json',
        body='{"status": "ok"}')

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')
    resp = jwp_client.a.b.c.d.f.e(abcde='')

    assert resp['status'] == 'ok'
예제 #12
0
def lambda_handler(event, context):
    #define SQS & AWS params
    sqs = boto3.client('sqs')
    queue_url = 'https://sqs.us-east-2.amazonaws.com/399317258909/accu-jw-poll'

    # Key & secret for JW Platform API calls
    # Configurations
    vkey = 'YYYYYYYY'
    vsecret = 'XXXXXXXXXXXXXXXXXXX'

    # Define JW Player
    jwplatform_client = jwplatform.Client(vkey, vsecret)

    # default new_messages to True so we can start polling
    # set rate limit to 40, don't want to stall any other processes
    new_messages = True
    min_rate_limit = 40

    # Check if there are messages in the response
    while new_messages and min_rate_limit >= 40:
        try:
            # Get a message from the queue, if there is one
            resp = sqs.receive_message(QueueUrl=queue_url,
                                       AttributeNames=['All'])

            # get the Media Id
            jw_media_id = resp['Messages'][0]['Body']
            sqs_receipt = resp['Messages'][0]['ReceiptHandle']

            # Check if status of media is ready & min_rate_limit >= 40
            # if so, make the API call & check to make sure it was successful. Else, exit()
            # if it's successful, delete the msg, log our rate limit, and move on to next msg
            api_response = jwplatform_client.videos.show(video_key=jw_media_id)

            if api_response['video'][
                    'status'] == "ready" and min_rate_limit >= 40:
                thumb_response = jwplatform_client.videos.thumbnails.update(
                    video_key=jw_media_id, position=3)
                min_rate_limit = thumb_response['rate_limit']['remaining']

                if thumb_response['status'] == "ok":
                    sqs.delete_message(QueueUrl=queue_url,
                                       ReceiptHandle=sqs_receipt)
            else:
                # If it's not "ready", set min_rate_limit & move on to next msg in queue
                min_rate_limit = thumb_response['rate_limit']['remaining']

        except KeyError:
            return 'No more messages on the queue!'
            messages = []
            new_messages = False
예제 #13
0
def test_post_parameters_in_body():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/a/b/c/d\?.*')
    responses.add(
        responses.POST, url_expr,
        status=200,
        content_type='application/json',
        body='{"status": "ok"}')

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')

    # ConnectionError is expected as request parameters are included in the
    # request body for POST request by default.
    with pytest.raises(ConnectionError):
        resp = jwp_client.a.b.c.d(http_method='POST', post='true', _body='none')
예제 #14
0
def test_long_resource():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/json/error\?.*')
    responses.add(
        responses.GET, url_expr,
        status=200,
        content_type='application/json',
        body='({"json": "error"})')

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')

    with pytest.raises(jwplatform.errors.JWPlatformUnknownError) as err:
        jwp_client.json.error()

    assert err.value.message == 'Not a valid JSON string: ({"json": "error"})'
예제 #15
0
def test_non_json_response_parsing():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/error\?.*')

    responses.add(
        responses.GET, url_expr,
        status=502,
        content_type='text/html',
        body='502 Bad Gateway')

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')

    with pytest.raises(jwplatform.errors.JWPlatformUnknownError) as err:
        jwp_client.error()

    assert err.value.message == 'Not a valid JSON string: 502 Bad Gateway'
예제 #16
0
def test_supported_errors_parsing(test_case):
    url_expr = re.compile(r'https?://api\.test\.tst/v1/error\?.*')

    responses.add(
        responses.GET, url_expr,
        status=test_case['http_status'],
        content_type='application/json',
        body=json.dumps(test_case['response']))

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')

    with pytest.raises(test_case['expected_exception']) as err:
        jwp_client.error()

    assert err.value.message == test_case['response']['message']
예제 #17
0
def replace_video(api_key, api_secret, local_video_path, video_key, **kwargs):
    """
    Function which allows to replace the content of an EXISTING video object.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param local_video_path: <string> Path to media on local machine.
    :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
    :return:
    """
    filename = os.path.basename(local_video_path)

    # Setup API client
    jwplatform_client = jwplatform.Client(api_key, api_secret)
    logging.info("Updating Video")
    try:
        response = jwplatform_client.videos.update(video_key=video_key,
                                                   upload_method='s3',
                                                   update_file='True',
                                                   **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error("Encountered an error updating the video\n{}".format(e))
        sys.exit(e.message)
    logging.info(response)

    # Construct base url for upload
    upload_url = '{}://{}{}'.format(response['link']['protocol'],
                                    response['link']['address'],
                                    response['link']['path'])

    # Query parameters for the upload
    query_parameters = response['link']['query']

    # HTTP PUT upload using requests
    headers = {
        'Content-Disposition': 'attachment; filename="{}"'.format(filename)
    }
    with open(local_video_path, 'rb') as f:
        r = requests.put(upload_url,
                         params=query_parameters,
                         headers=headers,
                         data=f)
        logging.info('uploading file {} to url {}'.format(
            local_video_path, r.url))
        logging.info('upload response: {}'.format(r.text))
        logging.info(r)
예제 #18
0
def test_default_initialization():

    KEY = 'api_key'
    SECRET = 'api_secret'

    jwp_client = jwplatform.Client(KEY, SECRET)

    assert jwp_client._Client__key == KEY
    assert jwp_client._Client__secret == SECRET
    assert jwp_client._scheme == 'https'
    assert jwp_client._host == 'api.jwplatform.com'
    assert jwp_client._port == 80
    assert jwp_client._api_version == 'v1'
    assert jwp_client._agent is None
    assert 'User-Agent' in jwp_client._connection.headers
    assert jwp_client._connection.headers['User-Agent'] == \
        'python-jwplatform/{}'.format(jwplatform.__version__)
예제 #19
0
def test_nonexisting_resource():
    url_expr = re.compile(r'https?://api\.test\.tst/v1/videos/abcd/show\?.*'
                          'abcd_key=AbcdKey.*')
    responses.add(
        responses.GET, url_expr,
        status=404,
        content_type='application/json',
        body='{"status": "error", '
             '"message": "API method `/videos/abcd/show` not found", '
             '"code": "NotFound", "title": "Not Found"}')

    jwp_client = jwplatform.Client('api_key', 'api_secret', host='api.test.tst')

    with pytest.raises(jwplatform.errors.JWPlatformNotFoundError) as err:
        jwp_client.videos.abcd.show(abcd_key='AbcdKey')

    assert err.value.message == 'API method `/videos/abcd/show` not found'
예제 #20
0
def create_video(api_key, api_secret, local_video_path, **kwargs):
    """
    Function which creates new video object via s3 upload method.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param local_video_path: <string> Path to media on local machine.
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jwplayer/reference#post_videos-create
    :return:
    """
    filename = os.path.basename(local_video_path)

    # Setup API client
    jwplatform_client = jwplatform.Client(api_key, api_secret)

    # Make /videos/create API call
    logging.info("creating video")
    try:
        response = jwplatform_client.videos.create(upload_method='s3',
                                                   **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error("Encountered an error creating a video\n{}".format(e))
        sys.exit(e.message)
    logging.info(response)

    # Construct base url for upload
    upload_url = '{}://{}{}'.format(response['link']['protocol'],
                                    response['link']['address'],
                                    response['link']['path'])

    # Query parameters for the upload
    query_parameters = response['link']['query']

    # HTTP PUT upload using requests
    headers = {
        'Content-Disposition': 'attachment; filename="{}"'.format(filename)
    }
    with open(local_video_path, 'rb') as f:
        r = requests.put(upload_url,
                         params=query_parameters,
                         headers=headers,
                         data=f)
        logging.info('uploading file {} to url {}'.format(
            local_video_path, r.url))
        logging.info('upload response: {}'.format(r.text))
        logging.info(r)
예제 #21
0
def get_jwplatform_client():
    """
    Examine the environment and return an authenticated jwplatform.Client instance. Raises
    JWPlatformClientError if credentials are not available

    """
    api_key = os.environ.get('JWPLAYER_API_KEY')
    if api_key is None:
        raise JWPlatformClientError(
            'Set jwplayer API key in JWPLAYER_API_KEY environment '
            'variable')

    api_secret = os.environ.get('JWPLAYER_API_SECRET')
    if api_secret is None:
        raise JWPlatformClientError(
            'Set jwplayer API secret in JWPLAYER_API_SECRET environment '
            'variable')

    return jwplatform.Client(api_key, api_secret)
def create_video(api_key, api_secret, local_video_path, api_format='json', **kwargs):
    """
    Function which creates new video object via multipart upload method.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param local_video_path: <string> Path to media on local machine.
    :param api_format: <string> REQUIRED Acceptable values include 'py','xml','json',and 'php'
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
    :return:
    """
    # Setup API client
    jwplatform_client = jwplatform.Client(api_key, api_secret)

    # Make /videos/create API call
    logging.info("Registering new Video-Object")
    try:
        response = jwplatform_client.videos.create(upload_method='multipart', **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error("Encountered an error creating a video\n{}".format(e))
    logging.info(response)

    # Construct base url for upload
    upload_url = '{}://{}{}'.format(
        response['link']['protocol'],
        response['link']['address'],
        response['link']['path']
    )

    # Query parameters for the upload
    query_parameters = response['link']['query']
    query_parameters['api_format'] = api_format
    headers = {'X-Session-ID': response['session_id']}

    with open(local_video_path, 'rb') as f:
        files = {'file': f}
        r = requests.post(upload_url,
                          params=query_parameters,
                          headers=headers,
                          files=files)
        logging.info('uploading file {} to url {}'.format(local_video_path, r.url))
        logging.info('upload response: {}'.format(r.text))
        logging.info(r)
예제 #23
0
def update_video(api_key, api_secret, video_key, **kwargs):
    """
    Function which allows you to update a video

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/update.html
    :return:
    """
    # Setup API client
    jwplatform_client = jwplatform.Client(api_key, api_secret)
    logging.info("Updating Video")
    try:
        response = jwplatform_client.videos.update(video_key=video_key,
                                                   **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error("Encountered an error updating the video\n{}".format(e))
        sys.exit(e.message)
    logging.info(response)
예제 #24
0
def create_channel(api_key, api_secret, channel_type='manual', **kwargs):
    """
    Function which creates a new channel. Channels serve as containers of video/media objects.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param channel_type: <string> REQUIRED Acceptable values include 'manual','dynamic','trending','feed','search'
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/channels/create.html
    :return: <dict> Dict which represents the JSON response.
    """
    jwplatform_client = jwplatform.Client(api_key, api_secret)
    logging.info("Creating new channel with keyword args.")
    try:
        response = jwplatform_client.channels.create(type=channel_type,
                                                     **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error(
            "Encountered an error creating new channel.\n{}".format(e))
        sys.exit(e.message)
    return response
예제 #25
0
def test_signature():

    KEY = 'api_key'
    SECRET = 'api_secret'
    PATH = '/test/resource/show'

    request_params = {
        'a': 1,
        'b': 'two',
        'c3': 'Param 3',
        u'❄': u'⛄',
        't1': True,
        'n0': None
    }

    jwp_client = jwplatform.Client(KEY, SECRET)

    url, params = jwp_client._build_request(PATH, request_params)

    assert url == 'https://api.jwplatform.com/v1{}'.format(PATH)
    assert 'api_nonce' in params
    assert 'api_timestamp' in params
    assert 'api_key' in params
    assert 'api_format' in params
    assert 'api_kit' in params
    assert 'api_signature' in params

    request_params['api_nonce'] = params['api_nonce']
    request_params['api_timestamp'] = params['api_timestamp']
    request_params['api_key'] = params['api_key']
    request_params['api_format'] = params['api_format']
    request_params['api_kit'] = params['api_kit']

    base_str = '&'.join([
        '{}={}'.format(quote((unicode(key).encode('utf-8')), safe='~'),
                       quote((unicode(value).encode('utf-8')), safe='~'))
        for key, value in sorted(request_params.items())
    ])

    assert params['api_signature'] == hashlib.sha1('{}{}'.format(
        base_str, SECRET).encode('utf-8')).hexdigest()
예제 #26
0
def list_conversions(api_key, api_secret, video_key, **kwargs):
    """
    Function which retrieves a list of a video object's conversions.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/conversions/list.html
    :return: <dict> Dict which represents the JSON response.
    """
    jwplatform_client = jwplatform.Client(api_key, api_secret)
    logging.info("Querying for video conversions.")
    try:
        response = jwplatform_client.videos.conversions.list(
            video_key=video_key, **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error(
            "Encountered an error querying for video conversions.\n{}".format(
                e))
        sys.exit(e.message)
    return response
예제 #27
0
def update_thumbnail_via_upload(api_key, api_secret, video_key, local_video_image_path='', api_format='json',
                                **kwargs):
    """
    Function which updates the thumbnail for a particular video object with a locally saved image.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param video_key: <string> Video's object ID. Can be found within JWPlayer Dashboard.
    :param local_video_image_path: <string> Local system path to an image.
    :param api_format: <string> REQUIRED Acceptable values include 'py','xml','json',and 'php'
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/thumbnails/update.html
    :return: <dict> Dict which represents the JSON response.
    """
    jwplatform_client = jwplatform.Client(api_key, api_secret)
    logging.info("Updating video thumbnail.")
    try:
        response = jwplatform_client.videos.thumbnails.update(
            video_key=video_key,
            **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error("Encountered an error updating thumbnail.\n{}".format(e))
        sys.exit(e.message)
    logging.info(response)

    # Construct base url for upload
    upload_url = '{}://{}{}'.format(
        response['link']['protocol'],
        response['link']['address'],
        response['link']['path']
    )

    # Query parameters for the upload
    query_parameters = response['link']['query']
    query_parameters['api_format'] = api_format

    with open(local_video_image_path, 'rb') as f:
        files = {'file': f}
        r = requests.post(upload_url, params=query_parameters, files=files)
        logging.info('uploading file {} to url {}'.format(local_video_image_path, r.url))
        logging.info('upload response: {}'.format(r.text))
예제 #28
0
def insert_into_channel(api_key, api_secret, channel_key, video_key, **kwargs):
    """
    Function which inserts video into a channel/playlist.

    :param api_key: <string> JWPlatform api-key
    :param api_secret: <string> JWPlatform shared-secret
    :param channel_key: <string> Key of the channel to which add a video.
    :param video_key: <string> Key of the video that should be added to the channel.
    :param kwargs: Arguments conforming to standards found @ https://developer.jwplayer.com/jw-platform/reference/v1/methods/videos/create.html
    :return: <dict> Dict which represents the JSON response.
    """
    jwplatform_client = jwplatform.Client(api_key, api_secret)
    logging.info("Inserting video into channel")
    try:
        response = jwplatform_client.channels.videos.create(
            channel_key=channel_key, video_key=video_key, **kwargs)
    except jwplatform.errors.JWPlatformError as e:
        logging.error(
            "Encountered an error inserting {} into channel {}.\n{}".format(
                video_key, channel_key, e))
        sys.exit(e.message)
    return response
예제 #29
0
def test_request_url():

    KEY = '_key_'
    SECRET = '_secret_'
    SCHEME = 'http'
    HOST = 'api.host.domain'
    PORT = 8080
    API_VERSION = 'v3'
    AGENT = 'test_request_url'
    PATH = '/a/b/c/d'

    jwp_client = jwplatform.Client(KEY,
                                   SECRET,
                                   scheme=SCHEME,
                                   host=HOST,
                                   port=PORT,
                                   version=API_VERSION,
                                   agent=AGENT)

    url, params = jwp_client._build_request(PATH)

    assert url == '{scheme}://{host}:{port}/{version}{path}'.format(
        scheme=SCHEME, host=HOST, port=PORT, version=API_VERSION, path=PATH)
예제 #30
0
def lambda_handler(event, context):
    #define S3, SQS & AWS params
    s3 = boto3.resource('s3')
    s3Client = boto3.client('s3')
    bucket_name = event['Records'][0]['s3']['bucket']['name'];
    key = event['Records'][0]['s3']['object']['key'];
    file_path = key.split(".")[0]
    file_type = key.split(".")[1]
    bucket_url = f"https://s3.us-east-2.amazonaws.com/{bucket_name}/"
    
    # SQS Config
    sqs = boto3.client('sqs')
    queue_url = 'https://sqs.us-east-2.amazonaws.com/399317258909/accu-jw-poll'
    
    # Key & secret for JW Platform API calls
    # Configurations
    vkey = ''
    vsecret = ''
    
    # Define JW Player
    
    jwplatform_client = jwplatform.Client(vkey, vsecret)
    
    # By default this means we are only uploading a new file, not updating one
    update_asset = 3
    
    #declare False values for our data and video
    data_file_path = False
    video_file_path = False
    captions_file_path = False

    #define our inner functions for repeated use
    def XMLtoJSON(file):
        with requests.Session() as s:
            download = s.get(file)
            dc = download.content.decode('utf-8')
             
        jsonString = json.dumps(xmltodict.parse(dc, process_namespaces=True))
        return json.loads(jsonString)
        
    def checkForFile(file, bucket):
        # try to hit this the file with a HEAD request
        # should check for any captions or metadata tracks too
        try:
            s3.Object(bucket, file).load()
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == "404":
                
                return e.response
                
            else:
                
                return e.response
        else:
            return True
    
    def publicUrl(file):
        
        pub_file = s3Client.generate_presigned_url('get_object', Params = {'Bucket': bucket_name, 'Key': file}, ExpiresIn = 1000)    
        return pub_file
        
    def uploadCaptions(api_response, captions_file_path, label):
        captions_obj = {}
        captions_obj['video_key'] = api_response.get('video',{'key': 'NA'})['key']
        captions_obj['kind'] = "captions"
        captions_obj['label'] = label
        response = jwplatform_client.videos.tracks.create(**captions_obj)
        
        # Construct base url for upload
        upload_url = '{}://{}{}'.format(
            response['link']['protocol'],
            response['link']['address'],
            response['link']['path']
        )
    
        # Query parameters for the upload
        query_parameters = response['link']['query']
        query_parameters['api_format'] = "json"
        
        http = urllib3.PoolManager()

        url = publicUrl(captions_file_path)
        response = http.request('GET', url)
        f = response.data
        
        files = {'file': f}
        r = requests.post(upload_url, params=query_parameters, files=files)
        
        return r    
    
    def getKeyFromHashCode(hash_code):
        search_params = {}
        search_params['search:custom.hash_code'] = hash_code
        get_media_key = jwplatform_client.videos.list(**search_params)
        
        return get_media_key['videos'][0]['key']
        
    def sendSQS(queue_url, media_id):
        response = sqs.send_message(
            QueueUrl=queue_url,
            MessageBody=(
                media_id
            )
        )
        
        return response
    
    #check if the file is an mp4 or not
    if file_type == "mp4":
        
        video_file_path = bucket_url + file_path + ".mp4"
        if checkForFile(file_path + ".xml", bucket_name):
            
            xml_url = publicUrl(file_path + ".xml")
            data_file_path = XMLtoJSON(xml_url)
            data_type = "xml"
            
        else:
            
            #metadata isn't here yet, we abort
            return "No metadata"
        
    else:
        
        # Event file is not an mp4 file, let's see if we have one in the bucket
        if checkForFile(file_path + ".mp4", bucket_name):
            
            video_file_path = bucket_url + file_path + ".mp4"
            
            # Now let's check what file triggered the event
            # If not XML, assumed DFXP and ignore
            if file_type == "xml":
                xml_url = publicUrl(file_path + ".xml")
                data_file_path = XMLtoJSON(xml_url)
                data_type = "xml"
            
            else:
                
                # Bad file type, Abort
                return "DFXP, not xml"
            
        else:
            
            #file isn't here yet, we abort
            return False
    
    if video_file_path and data_file_path:
        
        media_object = {}
        
        if data_type == "xml":
            
            # Parse data from XML
            
            # Set Video Path
            if data_file_path["publisher-upload-manifest"]["asset"][0]["@filename"]:
                video_file = data_file_path["publisher-upload-manifest"]["asset"][0]["@filename"]
                media_object["download_url"] = publicUrl(video_file)
                
            # Get Title of Video
            if data_file_path["publisher-upload-manifest"]["title"]["@name"]:
                media_object["title"] = data_file_path["publisher-upload-manifest"]["title"]["@name"]
            
            # Get Description if one exists
            if data_file_path["publisher-upload-manifest"]["title"]["short-description"]:
                media_object["description"] = data_file_path["publisher-upload-manifest"]["title"]["short-description"]
            
            # Generate Tags
            if data_file_path["publisher-upload-manifest"]["title"]["tag"]:
                media_object["tags"] = ','.join(map(str, data_file_path["publisher-upload-manifest"]["title"]["tag"]))
                
            # Start Date
            if data_file_path["publisher-upload-manifest"]["title"]["@start-date"]:
                date = data_file_path["publisher-upload-manifest"]["title"]["@start-date"]
                date = datetime.datetime.strptime(date, "%m/%d/%Y %H:%M %p")
                
                # +28800 to add 8 hours for UTC offset to EST
                media_object["date"] = calendar.timegm(date.utctimetuple()) + 28800
            
            # End Date
            if data_file_path["publisher-upload-manifest"]["title"]["@end-date"]:
                expire_date = data_file_path["publisher-upload-manifest"]["title"]["@end-date"]
                expire_date = datetime.datetime.strptime(expire_date, "%m/%d/%Y %H:%M %p")
                
                # +28800 to add 8 hours for UTC offset to EST
                media_object["expire_date"] = calendar.timegm(expire_date.utctimetuple()) + 28800
            
            # Get GUID for asset
            if data_file_path["publisher-upload-manifest"]["asset"][0]["@hash-code"]:
                media_object["custom.hash_code"] = data_file_path["publisher-upload-manifest"]["asset"][0]["@hash-code"]
            
            if data_file_path["publisher-upload-manifest"]["asset"][1]["@filename"]:
                captions_file_path = data_file_path["publisher-upload-manifest"]["asset"][1]["@filename"]
                
            # Check if this is an update or a new asset    
            if data_file_path["publisher-upload-manifest"]["reencode-from-new-source"]["@new-source-refid"]:
                
                update_asset = int(data_file_path["publisher-upload-manifest"]["reencode-from-new-source"]["@replace"])
                
        else:
            return "Not valid XML"
            
        # Check to see if this is a new asset, or an update
        
        # 1 = create new 
        if update_asset == 1 or not update_asset:
            
            api_response = jwplatform_client.videos.create(**media_object)
            
            if captions_file_path:
               uploadCaptions(api_response, captions_file_path, "English")
            
            return api_response
            
        # 2 = update            
        elif update_asset and update_asset == 2:
            
            media_object['update_file'] = True
            jw_media_id = getKeyFromHashCode(media_object['custom.hash_code'])
            media_object['video_key'] = jw_media_id
            video_file = data_file_path["publisher-upload-manifest"]["reencode-from-new-source"]["@new-source-refid"]
            media_object['download_url'] = publicUrl(video_file)
            media_object['update_file'] = True
            
            api_response = jwplatform_client.videos.update(**media_object)
            
            if api_response['status'] == "ok":
                sendSQS(queue_url, jw_media_id)
            
        # 3 = update & create new
        else:
            
            api_response = jwplatform_client.videos.create(**media_object)
            
            if captions_file_path:
                uploadCaptions(api_response, captions_file_path, "English")

            video_file = data_file_path["publisher-upload-manifest"]["reencode-from-new-source"]["@new-source-refid"]
            media_object['download_url'] = publicUrl(video_file)
            media_object['update_file'] = True
            jw_media_id = getKeyFromHashCode(media_object['custom.hash_code'])
            media_object['video_key'] = jw_media_id
            
            api_update_response = jwplatform_client.videos.update(**media_object)
            
            if api_update_response['status'] == "ok":
                sendSQS(queue_url, jw_media_id)