/*
 * Copyright (C) 2016 Metrological Group B.V.
 * Copyright (C) 2016 Igalia S.L.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above
 *    copyright notice, this list of conditions and the following
 *    disclaimer in the documentation and/or other materials provided
 *    with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "MediaKeySession.h"

#if ENABLE(ENCRYPTED_MEDIA)

#include "CDM.h"
#include "CDMInstance.h"
#include "Document.h"
#include "EventNames.h"
#include "MediaKeyMessageEvent.h"
#include "MediaKeyMessageType.h"
#include "EventNames.h"
#include "MediaKeyStatusMap.h"
#include "NotImplemented.h"
#include "SecurityOrigin.h"
#include "SharedBuffer.h"
#include <wtf/NeverDestroyed.h>
#include <wtf/text/Base64.h>

namespace WebCore {

typedef int (*LogFunction)(const char * format, ... );
extern LogFunction gMediaLog;

PassRefPtr<MediaKeySession> MediaKeySession::create(ScriptExecutionContext* context, MediaKeySessionType sessionType, bool useDistinctiveIdentifier, RefPtr<CDM> implementation, RefPtr<CDMInstance> instance)
{
	RefPtr<MediaKeySession> session = adoptRef(new MediaKeySession(context, sessionType, useDistinctiveIdentifier, implementation, instance));
    session->suspendIfNeeded();
    return session;
}

MediaKeySession::MediaKeySession(ScriptExecutionContext* context, MediaKeySessionType sessionType, bool useDistinctiveIdentifier, RefPtr<CDM> implementation, RefPtr<CDMInstance> instance)
: ActiveDOMObject(context)
, m_expiration(std::numeric_limits<double>::quiet_NaN())
, m_keyStatuses(MediaKeyStatusMap::create(*this))
, m_closed(false)
, m_uninitialized(true)
, m_callable(false)
, m_useDistinctiveIdentifier(useDistinctiveIdentifier)
, m_sessionType(sessionType)
, m_implementation(implementation)
, m_instance(instance)
, m_eventQueue(this)
, m_firstDecryptTime(0)
, m_latestDecryptTime(0)
{
    // https://w3c.github.io/encrypted-media/#dom-mediakeys-setservercertificate
    // W3C Editor's Draft 09 November 2016
    // createSession(), ctd.

    // 3.1. Let the sessionId attribute be the empty string.
    // 3.2. Let the expiration attribute be NaN.
    // 3.3. Let the closed attribute be a new promise.
    // 3.4. Let key status be a new empty MediaKeyStatusMap object, and initialize it as follows:
    // 3.4.1. Let the size attribute be 0.
    // 3.5. Let the session type value be sessionType.
    // 3.6. Let the uninitialized value be true.
    // 3.7. Let the callable value be false.
    // 3.8. Let the use distinctive identifier value be this object's use distinctive identifier value.
    // 3.9. Let the cdm implementation value be this object's cdm implementation.
    // 3.10. Let the cdm instance value be this object's cdm instance.

    UNUSED_PARAM(m_callable);
    UNUSED_PARAM(m_sessionType);
    UNUSED_PARAM(m_useDistinctiveIdentifier);
    UNUSED_PARAM(m_closed);
    UNUSED_PARAM(m_uninitialized);
}

MediaKeySession::~MediaKeySession()
{
	m_instance->closedSession(m_sessionId);
    m_keyStatuses->detachSession();
}

const String& MediaKeySession::sessionId() const
{
    return m_sessionId;
}

double MediaKeySession::expiration() const
{
    return m_expiration;
}

RefPtr<MediaKeyStatusMap> MediaKeySession::keyStatuses() const
{
    return m_keyStatuses;
}

MediaKeySession::GenerateRequestTask::GenerateRequestTask(MediaKeySession* mediaKeySession, RefPtr<SharedBuffer> initData, const AtomicString& initDataType, PromiseVoid promise)
: GenericTask<MediaKeySession>(mediaKeySession->createWeakPtr())
, initData(initData)
, initDataType(initDataType)
, promise(promise)
{
}

MediaKeySession::GenerateRequestTask::~GenerateRequestTask()
{
}

MediaKeySession::LicenseCallbackImpl::LicenseCallbackImpl(WeakPtr<MediaKeySession> weakThis, PromiseVoid promise)
: weakThis(weakThis)
, promise(promise)
{
}

MediaKeySession::LicenseCallbackImpl::~LicenseCallbackImpl()
{
}

MediaKeySession::LicenseFinishTask::LicenseFinishTask(WeakPtr<MediaKeySession> weakThis, PromiseVoid promise, RefPtr<SharedBuffer> message, MediaKeyMessageType messageType, String sessionId, CDMInstance::SuccessValue succeeded)
: GenericTask<MediaKeySession>(weakThis)
, promise(promise)
, message(message)
, messageType(messageType)
, sessionId(sessionId)
, succeeded(succeeded)
{
}

MediaKeySession::LicenseFinishTask::~LicenseFinishTask()
{
}

void MediaKeySession::LicenseFinishTask::exec()
{
	if (!weakThis) {
		promise.reject(INVALID_STATE_ERR);
		return;
	}

	// 10.10.1. If any of the preceding steps failed, reject promise with a new DOMException whose name is the appropriate error name.
	if (succeeded == CDMInstance::Failed) {
		promise.reject(NOT_SUPPORTED_ERR);
		return;
	}
	// 10.10.2. Set the sessionId attribute to session id.
	weakThis->m_sessionId = sessionId;

	// 10.9.3. Let this object's callable value be true.
	weakThis->m_callable = true;

	// 10.9.3. Run the Queue a "message" Event algorithm on the session, providing message type and message.
	weakThis->enqueueMessage(messageType, *message);

	// 10.9.3. Resolve promise.
	promise.resolve(std::nullptr_t());
}

void MediaKeySession::LicenseCallbackImpl::exec(RefPtr<SharedBuffer> message, const String& sessionId, bool needsIndividualization, CDMInstance::SuccessValue succeeded)
{
	if (!weakThis){
		promise.reject(INVALID_STATE_ERR);
		return;
	}

	// 10.9.3. Let session id be a unique Session ID string.

	MediaKeyMessageType messageType;
	if (!needsIndividualization) {
		// 10.9.4. If a license request for the requested license type can be generated based on the sanitized init data:
		// 10.9.4.1. Let message be a license request for the requested license type generated based on the sanitized init data interpreted per initDataType.
		// 10.9.4.2. Let message type be "license-request".
		messageType = MediaKeyMessageType::LicenseRequest;
	} else {
		// 10.9.5. Otherwise:
		// 10.9.5.1. Let message be the request that needs to be processed before a license request request for the requested license
		//           type can be generated based on the sanitized init data.
		// 10.9.5.2. Let message type reflect the type of message, either "license-request" or "individualization-request".
		messageType = MediaKeyMessageType::IndividualizationRequest;
	}

	// 10.10. Queue a task to run the following steps:
	weakThis->m_taskQueue.enqueueTask(adoptPtr(new LicenseFinishTask(weakThis, promise, message, messageType, sessionId, succeeded)));
}

void MediaKeySession::GenerateRequestTask::exec()
{
	if (!weakThis) {
		promise.reject(INVALID_STATE_ERR);
		return;
	}

	// 10.1. If the init data is not valid for initDataType, reject promise with a newly created TypeError.
	// 10.2. Let sanitized init data be a validated and sanitized version of init data.
	RefPtr<SharedBuffer> sanitizedInitData = weakThis->m_implementation->sanitizeInitData(initDataType, *initData);

	// 10.3. If the preceding step failed, reject promise with a newly created TypeError.
	if (!sanitizedInitData) {
		promise.reject(TypeError);
		return;
	}

	// 10.4. If sanitized init data is empty, reject promise with a NotSupportedError.
	if (sanitizedInitData->isEmpty()) {
		promise.reject(NOT_SUPPORTED_ERR);
		return;
	}

	// 10.5. Let session id be the empty string.
	// 10.6. Let message be null.
	// 10.7. Let message type be null.
	// 10.8. Let cdm be the CDM instance represented by this object's cdm instance value.
	// 10.9. Use the cdm to execute the following steps:
	// 10.9.1. If the sanitized init data is not supported by the cdm, reject promise with a NotSupportedError.
	if (!weakThis->m_implementation->supportsInitData(initDataType, *sanitizedInitData)) {
		promise.reject(NOT_SUPPORTED_ERR);
		return;
	}

	// 10.9.2 Follow the steps for the value of session type from the following list:
	// "temporary"
	// Let requested license type be a temporary non-persistable license.
	// "persistent-license"
	// Let requested license type be a persistable license.
	// "persistent-usage-record"
	// 1. Initialize this object's record of key usage as follows.
	//    Set the list of key IDs known to the session to an empty list.
	//    Set the first decrypt time to null.
	//    Set the latest decrypt time to null.
	// 2. Let requested license type be a non-persistable license that will
	//    persist a record of key usage.

	if (weakThis->m_sessionType == MediaKeySessionType::PersistentUsageRecord) {
		weakThis->m_recordOfKeyUsage.clear();
		weakThis->m_firstDecryptTime = 0;
		weakThis->m_latestDecryptTime = 0;
	}

	weakThis->m_instance->requestLicense(weakThis->m_sessionType, initDataType, initData, adoptPtr(new LicenseCallbackImpl(weakThis, promise)));
}

void MediaKeySession::generateRequest(const AtomicString& initDataType, const BufferSource& initData, PromiseVoid promise)
{
    // https://w3c.github.io/encrypted-media/#dom-mediakeysession-generaterequest
    // W3C Editor's Draft 09 November 2016

    // When this method is invoked, the user agent must run the following steps:
    // 1. If this object is closed, return a promise rejected with an InvalidStateError.
    // 2. If this object's uninitialized value is false, return a promise rejected with an InvalidStateError.
    if (m_closed || !m_uninitialized) {
        promise.reject(INVALID_STATE_ERR);
        return;
    }

    // 3. Let this object's uninitialized value be false.
    m_uninitialized = false;

    // 4. If initDataType is the empty string, return a promise rejected with a newly created TypeError.
    // 5. If initData is an empty array, return a promise rejected with a newly created TypeError.
    if (initDataType.isEmpty() || !initData.length()) {
        promise.reject(TypeError);
        return;
    }

    // 6. If the Key System implementation represented by this object's cdm implementation value does not support
    //    initDataType as an Initialization Data Type, return a promise rejected with a NotSupportedError. String
    //    comparison is case-sensitive.
    if (!m_implementation->supportsInitDataType(initDataType)) {
        promise.reject(NOT_SUPPORTED_ERR);
        return;
    }

    // 7. Let init data be a copy of the contents of the initData parameter.
    // 8. Let session type be this object's session type.
    // 9. Let promise be a new promise.
    // 10. Run the following steps in parallel:
    m_taskQueue.enqueueTask(adoptPtr(new GenerateRequestTask(this, SharedBuffer::create(initData.data(), initData.length()), initDataType, promise)));

    // 11. Return promise.
}

MediaKeySession::LoadTask::LoadTask(MediaKeySession* mediaKeySession, const String& sessionId, PromiseBool promise)
: GenericTask<MediaKeySession>(mediaKeySession->createWeakPtr())
, sessionId(sessionId)
, promise(promise)
{
}

MediaKeySession::LoadTask::~LoadTask()
{
}

MediaKeySession::LoadSessionCallbackImpl::LoadSessionCallbackImpl(WeakPtr<MediaKeySession> weakThis, PromiseBool promise, const String& sanitizedSessionId)
: weakThis(weakThis)
, sanitizedSessionId(sanitizedSessionId)
, promise(promise)
{
}

MediaKeySession::LoadSessionCallbackImpl::~LoadSessionCallbackImpl()
{
}

MediaKeySession::LoadFinishTask::LoadFinishTask(WeakPtr<MediaKeySession> weakThis, Optional<CDMInstance::KeyStatusVector> knownKeys, Optional<double> expiration, Optional<CDMInstance::Message> message, const String& sanitizedSessionId, CDMInstance::SuccessValue succeeded, PromiseBool promise)
: GenericTask<MediaKeySession>(weakThis)
, knownKeys(knownKeys)
, expiration(expiration)
, message(message)
, sanitizedSessionId(sanitizedSessionId)
, succeeded(succeeded)
, promise(promise)
{
}

MediaKeySession::LoadFinishTask::~LoadFinishTask()
{
}

void MediaKeySession::LoadFinishTask::exec()
{
	if(!weakThis)
		return;

	// 8.9.1. If any of the preceding steps failed, reject promise with a the appropriate error name.
	if (succeeded == CDMInstance::Failed) {
		promise.reject(NOT_SUPPORTED_ERR);
		return;
	}

	// 8.9.2. Set the sessionId attribute to sanitized session ID.
	// 8.9.3. Let this object's callable value be true.
	weakThis->m_sessionId = sanitizedSessionId;
	weakThis->m_callable = true;

	// 8.9.4. If the loaded session contains information about any keys (there are known keys), run the Update Key Statuses algorithm on the session, providing each key's key ID along with the appropriate MediaKeyStatus.
	if (knownKeys)
		weakThis->updateKeyStatuses(knownKeys.value());

	// 8.9.5. Run the Update Expiration algorithm on the session, providing expiration time.
	// This must be run, and NaN is the default value if the CDM instance doesn't provide one.
	weakThis->updateExpiration(expiration.valueOr(std::numeric_limits<double>::quiet_NaN()));

	// 8.9.6. If message is not null, run the Queue a "message" Event algorithm on the session, providing message type and message.
	if (message)
		weakThis->enqueueMessage(message.value().first, *message.value().second);

	// 8.9.7. Resolve promise with true.
	promise.resolve(true);
}

void MediaKeySession::LoadSessionCallbackImpl::exec(Optional<CDMInstance::KeyStatusVector> knownKeys, Optional<double> expiration, Optional<CDMInstance::Message> message, CDMInstance::SuccessValue succeeded, CDMInstance::SessionLoadFailure failure)
{
	if(!weakThis)
		return;

	// 8.8.1. If there is no data stored for the sanitized session ID in the origin, resolve promise with false and abort these steps.
    // 8.8.2. If the stored session's session type is not the same as the current MediaKeySession session type, reject promise with a newly created TypeError.
    // 8.8.3. Let session data be the data stored for the sanitized session ID in the origin. This must not include data from other origin(s) or that is not associated with an origin.
    // 8.8.4. If there is a MediaKeySession object that is not closed in any Document and that represents the session data, reject promise with a QuotaExceededError.
    // 8.8.5. Load the session data.
    // 8.8.6. If the session data indicates an expiration time for the session, let expiration time be the expiration time in milliseconds since 01 January 1970 UTC.
    // 8.8.7. If the CDM needs to send a message:
    //   8.8.7.1. Let message be a message generated by the CDM based on the session data.
    //   8.8.7.2. Let message type be the appropriate MediaKeyMessageType for the message.
    // NOTE: Steps 8.8.1. through 8.8.7. should be implemented in CDMInstance.

    if (succeeded == CDMInstance::Failed) {
        switch (failure) {
        case CDMInstance::NoSessionData:
            promise.resolve(false);
            return;
        case CDMInstance::MismatchedSessionType:
            promise.reject(TypeError);
            return;
        case CDMInstance::QuotaExceeded:
            promise.reject(QUOTA_EXCEEDED_ERR);
            return;
        case CDMInstance::None:
        case CDMInstance::Other:
            // In any other case, the session load failure will cause a rejection in the following task.
            break;
        }
    }

    // 8.9. Queue a task to run the following steps:
    weakThis->m_taskQueue.enqueueTask(adoptPtr(new LoadFinishTask(weakThis, knownKeys, expiration, message, sanitizedSessionId, succeeded, promise)));
}

void MediaKeySession::LoadTask::exec()
{
	if(!weakThis)
		return;

    // 8.1. Let sanitized session ID be a validated and/or sanitized version of sessionId.
    // 8.2. If the preceding step failed, or if sanitized session ID is empty, reject promise with a newly created TypeError.
    Optional<String> sanitizedSessionId = weakThis->m_implementation->sanitizeSessionId(sessionId);
    if (!sanitizedSessionId || sanitizedSessionId.value().isEmpty()) {
        promise.reject(TypeError);
        return;
    }

    // 8.3. If there is a MediaKeySession object that is not closed in this object's Document whose sessionId attribute is sanitized session ID, reject promise with a QuotaExceededError.
    // FIXME: This needs a global MediaKeySession tracker.

    String origin;
    if (Document* document = static_cast<Document*>(weakThis->scriptExecutionContext()))
        origin = document->securityOrigin()->toString();

    // 8.4. Let expiration time be NaN.
    // 8.5. Let message be null.
    // 8.6. Let message type be null.
    // 8.7. Let cdm be the CDM instance represented by this object's cdm instance value.
    // 8.8. Use the cdm to execute the following steps:
    weakThis->m_instance->loadSession(weakThis->m_sessionType, sanitizedSessionId.value(), origin, adoptPtr(new LoadSessionCallbackImpl(weakThis, promise, sanitizedSessionId.value())));
}

void MediaKeySession::load(const String& sessionId, PromiseBool promise)
{
    // https://w3c.github.io/encrypted-media/#dom-mediakeysession-load
    // W3C Editor's Draft 09 November 2016

    // 1. If this object is closed, return a promise rejected with an InvalidStateError.
    // 2. If this object's uninitialized value is false, return a promise rejected with an InvalidStateError.
    if (m_closed || !m_uninitialized) {
        promise.reject(INVALID_STATE_ERR);
        return;
    }

    // 3. Let this object's uninitialized value be false.
    m_uninitialized = false;

    // 4. If sessionId is the empty string, return a promise rejected with a newly created TypeError.
    // 5. If the result of running the Is persistent session type? algorithm on this object's session type is false, return a promise rejected with a newly created TypeError.
    if (sessionId.isEmpty() || m_sessionType == MediaKeySessionType::Temporary) {
        promise.reject(TypeError);
        return;
    }

    // 6. Let origin be the origin of this object's Document.
    // This is retrieved in the following task.

    // 7. Let promise be a new promise.
    // 8. Run the following steps in parallel:
    m_taskQueue.enqueueTask(adoptPtr(new LoadTask(this, sessionId, promise)));

    // 9. Return promise.
}

MediaKeySession::UpdateTask::UpdateTask(MediaKeySession* mediaKeySession, RefPtr<SharedBuffer> response, PromiseVoid promise)
: GenericTask<MediaKeySession>(mediaKeySession->createWeakPtr())
, response(response)
, promise(promise)
{
}

MediaKeySession::UpdateTask::~UpdateTask()
{
}

MediaKeySession::LicenseUpdateCallbackImpl::LicenseUpdateCallbackImpl(WeakPtr<MediaKeySession> weakThis, PromiseVoid promise)
: weakThis(weakThis)
, promise(promise)
{
}

MediaKeySession::LicenseUpdateCallbackImpl::~LicenseUpdateCallbackImpl()
{
}

MediaKeySession::LicenseUpdateFinishTask::LicenseUpdateFinishTask(WeakPtr<MediaKeySession> weakThis, bool sessionWasClosed, Optional<CDMInstance::KeyStatusVector> changedKeys, Optional<double> changedExpiration, Optional<CDMInstance::Message> message, PromiseVoid promise)
: GenericTask<MediaKeySession>(weakThis)
, sessionWasClosed(sessionWasClosed)
, changedKeys(changedKeys)
, changedExpiration(changedExpiration)
, message(message)
, promise(promise)
{
}

MediaKeySession::LicenseUpdateFinishTask::~LicenseUpdateFinishTask()
{
}

void MediaKeySession::LicenseUpdateFinishTask::exec()
{
	if (!weakThis) {
		promise.reject(INVALID_STATE_ERR);
		return;
	}

	// 6.8.1.
	if (sessionWasClosed) {
		// If session closed is true:
		//   Run the Session Closed algorithm on this object.
		weakThis->sessionClosed();
	} else {
		// Otherwise:
		//   Run the following steps:
		//     6.8.1.1. If the set of keys known to the CDM for this object changed or the status of any key(s) changed, run the Update Key Statuses
		//              algorithm on the session, providing each known key's key ID along with the appropriate MediaKeyStatus. Should additional
		//              processing be necessary to determine with certainty the status of a key, use "status-pending". Once the additional processing
		//              for one or more keys has completed, run the Update Key Statuses algorithm again with the actual status(es).
		if (changedKeys)
			weakThis->updateKeyStatuses(changedKeys.value());

		//     6.8.1.2. If the expiration time for the session changed, run the Update Expiration algorithm on the session, providing the new expiration time.
		if (changedExpiration)
			weakThis->updateExpiration(changedExpiration.value());

		//     6.8.1.3. If any of the preceding steps failed, reject promise with a new DOMException whose name is the appropriate error name.
		// FIXME: At this point the implementations of preceding steps can't fail.

		//     6.8.1.4. If message is not null, run the Queue a "message" Event algorithm on the session, providing message type and message.
		if (message)
			weakThis->enqueueMessage(message.value().first, *message.value().second);
	}

	// 6.8.2. Resolve promise.
	promise.resolve(std::nullptr_t());
}

void MediaKeySession::LicenseUpdateCallbackImpl::exec(bool sessionWasClosed, Optional<CDMInstance::KeyStatusVector> changedKeys, Optional<double> changedExpiration, Optional<CDMInstance::Message> message, CDMInstance::SuccessValue succeeded)
{
	if (!weakThis)
		return;

	// 6.7.1. If the format of sanitized response is invalid in any way, reject promise with a newly created TypeError.
	// 6.7.2. Process sanitized response, following the stipulation for the first matching condition from the following list:
	//   If sanitized response contains a license or key(s)
	//     Process sanitized response, following the stipulation for the first matching condition from the following list:
	//     If sessionType is "temporary" and sanitized response does not specify that session data, including any license, key(s), or similar session data it contains, should be stored
	//       Process sanitized response, not storing any session data.
	//     If sessionType is "persistent-license" and sanitized response contains a persistable license
	//       Process sanitized response, storing the license/key(s) and related session data contained in sanitized response. Such data must be stored such that only the origin of this object's Document can access it.
	//     If sessionType is "persistent-usage-record" and sanitized response contains a non-persistable license
	//       Run the following steps:
	//         6.7.2.3.1. Process sanitized response, not storing any session data.
	//         6.7.2.3.2. If processing sanitized response results in the addition of keys to the set of known keys, add the key IDs of these keys to this object's record of key usage.
	//     Otherwise
	//       Reject promise with a newly created TypeError.
	//   If sanitized response contains a record of license destruction acknowledgement and sessionType is "persistent-license"
	//     Run the following steps:
	//       6.7.2.1. Close the key session and clear all stored session data associated with this object, including the sessionId and record of license destruction.
	//       6.7.2.2. Set session closed to true.
	//   Otherwise
	//     Process sanitized response, not storing any session data.
	// NOTE: Steps 6.7.1. and 6.7.2. should be implemented in CDMInstance.

	if (succeeded == CDMInstance::Failed) {
		promise.reject(TypeError);
		return;
	}

	// 6.7.3. If a message needs to be sent to the server, execute the following steps:
	//   6.7.3.1. Let message be that message.
	//   6.7.3.2. Let message type be the appropriate MediaKeyMessageType for the message.
	// 6.8. Queue a task to run the following steps:
	weakThis->m_taskQueue.enqueueTask(adoptPtr(new LicenseUpdateFinishTask(weakThis, sessionWasClosed, changedKeys, changedExpiration, message, promise)));
}

static bool extractAesDecryptorResponseInfo(RefPtr<SharedBuffer> response, CDMResponseInfo& responseInfo)
{
    // 1. Format
    // {"keys":[{"kty":"oct","kid":"YAYeAX5Hfod-V9ANHtANHg","k":"GoogleTestKeyBase64ggg"}]}
    String json(response->data(), response->size());

    gMediaLog("---->CDM extractResponseInfo(%s)\n", json.utf8().data());

    RefPtr<InspectorValue> value = InspectorValue::parseJSON(json);
    if (!value)
        return false;

    RefPtr<InspectorObject> keysObject;
    if (!value->asObject(&keysObject))
        return false;

    RefPtr<InspectorArray> keysArray = keysObject->getArray("keys");
    if (!keysArray)
        return false;

    for (InspectorArray::iterator it1 = keysArray->begin(); it1 != keysArray->end(); ++it1) {
        RefPtr<InspectorObject> keyObject;

        if (!(*it1)->asObject(&keyObject))
            return false;

        CDMKeyInfo keyInfo;

        for(InspectorObject::iterator it2 = keyObject->begin(); it2 != keyObject->end(); ++it2) {
        	String k = it2->first;
        	String v;

            if (!it2->second->asString(&v))
                return false;

            gMediaLog("  >CDM (%s=%s)\n", k.utf8().data(), v.utf8().data());

            if(k == ASCIILiteral("kid")) {
				if (!WTF::base64URLDecode(v, keyInfo.kid))
					return false;
            }
            else if(k == ASCIILiteral("k")) {
				Vector<char> vData;
				if (!WTF::base64URLDecode(v, keyInfo.k))
					return false;
			}
        }

        gMediaLog("  >CDM (kid length %i, k length %i)\n", keyInfo.kid.size(), keyInfo.k.size());

        responseInfo.keys.append(keyInfo);
    }

	return true;
}

void MediaKeySession::UpdateTask::exec()
{
	if (!weakThis) {
		promise.reject(INVALID_STATE_ERR);
		return;
	}

    // 6.1. Let sanitized response be a validated and/or sanitized version of response copy.
	CDMResponseInfo responseInfo;
	if(weakThis->m_instance->isAesDecryptor()) {
		if(!extractAesDecryptorResponseInfo(response, responseInfo)) {
			promise.reject(TypeError);
			return;
		}
	}

    RefPtr<SharedBuffer> sanitizedResponse = weakThis->m_implementation->sanitizeResponse(response, responseInfo, weakThis->m_instance->isAesDecryptor());

    // 6.2. If the preceding step failed, or if sanitized response is empty, reject promise with a newly created TypeError.
    if (!sanitizedResponse || sanitizedResponse->isEmpty()) {
        promise.reject(TypeError);
        return;
    }

    // 6.3. Let message be null.
    // 6.4. Let message type be null.
    // 6.5. Let session closed be false.
    // 6.6. Let cdm be the CDM instance represented by this object's cdm instance value.
    // 6.7. Use the cdm to execute the following steps:
    weakThis->m_instance->updateLicense(weakThis->m_sessionId, weakThis->m_sessionType, *sanitizedResponse, responseInfo, adoptPtr(new LicenseUpdateCallbackImpl(weakThis, promise)), adoptRef(new LicenseRenewCallbackImpl(weakThis)));
}

MediaKeySession::LicenseRenewCallbackImpl::LicenseRenewCallbackImpl(WeakPtr<MediaKeySession> weakThis)
: weakThis(weakThis)
{
}

MediaKeySession::LicenseRenewCallbackImpl::~LicenseRenewCallbackImpl()
{
}

void MediaKeySession::LicenseRenewCallbackImpl::exec(const unsigned char* message, unsigned messageLength)
{
	if(!weakThis)
		return;

	weakThis->enqueueMessage(MediaKeyMessageType::LicenseRenewal, message, messageLength);
}

void MediaKeySession::update(const BufferSource& response, PromiseVoid promise)
{
    // https://w3c.github.io/encrypted-media/#dom-mediakeysession-update
    // W3C Editor's Draft 09 November 2016

    // When this method is invoked, the user agent must run the following steps:
    // 1. If this object is closed, return a promise rejected with an InvalidStateError.
    // 2. If this object's callable value is false, return a promise rejected with an InvalidStateError.
    if (m_closed || !m_callable) {
        promise.reject(INVALID_STATE_ERR);
        return;
    }

    // 3. If response is an empty array, return a promise rejected with a newly created TypeError.
    if (!response.length()) {
        promise.reject(TypeError);
        return;
    }

    // 4. Let response copy be a copy of the contents of the response parameter.
    // 5. Let promise be a new promise.
    // 6. Run the following steps in parallel:
    m_taskQueue.enqueueTask(adoptPtr(new UpdateTask(this, SharedBuffer::create(response.data(), response.length()), promise)));

    // 7. Return promise.
}

MediaKeySession::CloseTask::CloseTask(MediaKeySession* mediaKeySession, PromiseVoid promise)
: GenericTask<MediaKeySession>(mediaKeySession->createWeakPtr())
, promise(promise)
{

}

MediaKeySession::CloseTask::~CloseTask()
{
}

MediaKeySession::CloseSessionCallbackImpl::CloseSessionCallbackImpl(WeakPtr<MediaKeySession> weakThis, PromiseVoid promise)
: weakThis(weakThis)
, promise(promise)
{
}

MediaKeySession::CloseSessionCallbackImpl::~CloseSessionCallbackImpl()
{
}

MediaKeySession::CloseFinishTask::CloseFinishTask(WeakPtr<MediaKeySession> weakThis, PromiseVoid promise)
: GenericTask<MediaKeySession>(weakThis)
, promise(promise)
{
}

MediaKeySession::CloseFinishTask::~CloseFinishTask()
{
}

void MediaKeySession::CloseFinishTask::exec()
{
    if (!weakThis)
        return;

    // 5.3.1. Run the Session Closed algorithm on the session.
	weakThis->sessionClosed();

    // 5.3.2. Resolve promise.
    promise.resolve(std::nullptr_t());
}

void MediaKeySession::CloseSessionCallbackImpl::exec()
{
    if (!weakThis)
        return;

    // 5.3. Queue a task to run the following steps:
    weakThis->m_taskQueue.enqueueTask(adoptPtr(new CloseFinishTask(weakThis, promise)));
}

void MediaKeySession::CloseTask::exec()
{
    if (!weakThis)
        return;

    // 5.1. Let cdm be the CDM instance represented by session's cdm instance value.
    // 5.2. Use cdm to close the key session associated with session.
	weakThis->m_instance->closeSession(weakThis->m_sessionId, adoptPtr(new CloseSessionCallbackImpl(weakThis, promise)));
}

void MediaKeySession::close(PromiseVoid promise)
{
    // https://w3c.github.io/encrypted-media/#dom-mediakeysession-close
    // W3C Editor's Draft 09 November 2016

    // 1. Let session be the associated MediaKeySession object.
    // 2. If session is closed, return a resolved promise.
    if (m_closed) {
        promise.resolve(std::nullptr_t());
        return;
    }

    // 3. If session's callable value is false, return a promise rejected with an InvalidStateError.
    if (!m_callable) {
        promise.reject(INVALID_STATE_ERR);
        return;
    }

    // 4. Let promise be a new promise.
    // 5. Run the following steps in parallel:
    m_taskQueue.enqueueTask(adoptPtr(new CloseTask(this, promise)));

    // 6. Return promise.
}

MediaKeySession::RemoveTask::RemoveTask(MediaKeySession* mediaKeySession, PromiseVoid promise)
: GenericTask<MediaKeySession>(weakThis)
, promise(promise)
{
}

MediaKeySession::RemoveTask::~RemoveTask()
{
}

MediaKeySession::RemoveFinishTask::RemoveFinishTask(WeakPtr<MediaKeySession> weakThis, const CDMInstance::KeyStatusVector& keys, Optional<RefPtr<SharedBuffer> > message, CDMInstance::SuccessValue succeeded, PromiseVoid promise)
: GenericTask<MediaKeySession>(weakThis)
, keys(keys)
, message(message)
, succeeded(succeeded)
, promise(promise)
{
}

MediaKeySession::RemoveFinishTask::~RemoveFinishTask()
{
}

MediaKeySession::RemoveSessionDataCallbackImpl::RemoveSessionDataCallbackImpl(WeakPtr<MediaKeySession> weakThis, PromiseVoid promise)
: weakThis(weakThis)
, promise(promise)
{
}

MediaKeySession::RemoveSessionDataCallbackImpl::~RemoveSessionDataCallbackImpl()
{
}

void MediaKeySession::RemoveSessionDataCallbackImpl::exec(const CDMInstance::KeyStatusVector& keys, Optional<RefPtr<SharedBuffer> > message, CDMInstance::SuccessValue succeeded)
{
	if (!weakThis)
		return;

	// 4.4.1. If any license(s) and/or key(s) are associated with the session:
	//   4.4.1.1. Destroy the license(s) and/or key(s) associated with the session.
	//   4.4.1.2. Follow the steps for the value of this object's session type from the following list:
	//     "temporary"
	//       4.4.1.2.1.1 Continue with the following steps.
	//     "persistent-license"
	//       4.4.1.2.2.1. Let record of license destruction be a record of license destruction for the license represented by this object.
	//       4.4.1.2.2.2. Store the record of license destruction.
	//       4.4.1.2.2.3. Let message be a message containing or reflecting the record of license destruction.
	//     "persistent-usage-record"
	//       4.4.1.2.3.1. Store this object's record of key usage.
	//       4.4.1.2.3.2. Let message be a message containing or reflecting this object's record of key usage.
	// NOTE: Step 4.4.1. should be implemented in CDMInstance.

	// 4.5. Queue a task to run the following steps:
	weakThis->m_taskQueue.enqueueTask(adoptPtr(new RemoveFinishTask(weakThis, keys, message, succeeded, promise)));
}

void MediaKeySession::RemoveTask::exec()
{
	if(!weakThis)
		return;

    // 4.1. Let cdm be the CDM instance represented by this object's cdm instance value.
    // 4.2. Let message be null.
    // 4.3. Let message type be null.

    // 4.4. Use the cdm to execute the following steps:
	weakThis->m_instance->removeSessionData(weakThis->m_sessionId, weakThis->m_sessionType, adoptPtr(new RemoveSessionDataCallbackImpl(weakThis, promise)));
}

void MediaKeySession::RemoveFinishTask::exec()
{
	if(!weakThis)
		return;

    // 4.5.1. Run the Update Key Statuses algorithm on the session, providing all key ID(s) in the session along with the "released" MediaKeyStatus value for each.
	weakThis->updateKeyStatuses(keys);

    // 4.5.2. Run the Update Expiration algorithm on the session, providing NaN.
	weakThis->updateExpiration(std::numeric_limits<double>::quiet_NaN());

    // 4.5.3. If any of the preceding steps failed, reject promise with a new DOMException whose name is the appropriate error name.
    if (succeeded == CDMInstance::Failed) {
        promise.reject(NOT_SUPPORTED_ERR);
        return;
    }

    // 4.5.4. Let message type be "license-release".
    // 4.5.5. If message is not null, run the Queue a "message" Event algorithm on the session, providing message type and message.
    if (message)
    	weakThis->enqueueMessage(MediaKeyMessageType::LicenseRelease, *message.value());

    // 4.5.6. Resolve promise.
    promise.resolve(std::nullptr_t());
}

void MediaKeySession::remove(PromiseVoid promise)
{
    // https://w3c.github.io/encrypted-media/#dom-mediakeysession-remove
    // W3C Editor's Draft 09 November 2016

    // 1. If this object is closed, return a promise rejected with an InvalidStateError.
    // 2. If this object's callable value is false, return a promise rejected with an InvalidStateError.
    if (m_closed || !m_callable) {
        promise.reject(INVALID_STATE_ERR);
        return;
    }

    // 3. Let promise be a new promise.
    // 4. Run the following steps in parallel:
    m_taskQueue.enqueueTask(adoptPtr(new RemoveTask(this, promise)));

    // 5. Return promise.
}

void MediaKeySession::registerClosedPromise(ClosedPromise promise)
{
    ASSERT(!m_closedPromise);
    if (m_closed) {
        promise.resolve(std::nullptr_t());
        return;
    }
    m_closedPromise = Optional<ClosedPromise>(promise);
}

void MediaKeySession::enqueueMessage(MediaKeyMessageType messageType, const unsigned char* message, unsigned messageLength)
{
    // 6.4.1 Queue a "message" Event
    // https://w3c.github.io/encrypted-media/#queue-message
    // W3C Editor's Draft 09 November 2016

    // The following steps are run:
    // 1. Let the session be the specified MediaKeySession object.
    // 2. Queue a task to create an event named message that does not bubble and is not cancellable using the MediaKeyMessageEvent
    //    interface with its type attribute set to message and its isTrusted attribute initialized to true, and dispatch it at the
    //    session.
	RefPtr<MediaKeyMessageEvent> messageEvent = MediaKeyMessageEvent::create(eventNames().messageEvent, MediaKeyMessageEventInit(false, false ,false, messageType, JSC::ArrayBuffer::create(message, messageLength)));
    m_eventQueue.enqueueEvent(messageEvent);
}

void MediaKeySession::enqueueMessage(MediaKeyMessageType messageType, const SharedBuffer& message)
{
	enqueueMessage(messageType, (const unsigned char* )message.data(), message.size());
}

void MediaKeySession::updateKeyStatuses(const CDMInstance::KeyStatusVector& inputStatuses)
{
    // https://w3c.github.io/encrypted-media/#update-key-statuses
    // W3C Editor's Draft 09 November 2016

    // 1. Let the session be the associated MediaKeySession object.
    // 2. Let the input statuses be the sequence of pairs key ID and associated MediaKeyStatus pairs.
    // 3. Let the statuses be session's keyStatuses attribute.
    // 4. Run the following steps to replace the contents of statuses:
    //   4.1. Empty statuses.
    //   4.2. For each pair in input statuses.
    //     4.2.1. Let pair be the pair.
    //     4.2.2. Insert an entry for pair's key ID into statuses with the value of pair's MediaKeyStatus value.


    m_statuses.clear();
    m_statuses.reserveCapacity(inputStatuses.size());
    for (int i = 0; i < inputStatuses.size(); ++i)
        m_statuses.uncheckedAppend(std::pair<RefPtr<SharedBuffer>, MediaKeyStatus>(inputStatuses[i].first, inputStatuses[i].second));

    // 5. Queue a task to fire a simple event named keystatuseschange at the session.
    m_eventQueue.enqueueEvent(Event::create(eventNames().keystatuseschangeEvent, false, false));

    // 6. Queue a task to run the Attempt to Resume Playback If Necessary algorithm on each of the media element(s) whose mediaKeys attribute is the MediaKeys object that created the session.
    // FIXME: Implement.
}

void MediaKeySession::updateExpiration(double)
{
    notImplemented();
}

void MediaKeySession::sessionClosed()
{
    // https://w3c.github.io/encrypted-media/#session-closed
    // W3C Editor's Draft 09 November 2016

    // 1. Let session be the associated MediaKeySession object.
    // 2. If session's session type is "persistent-usage-record", execute the following steps in parallel:
    if (m_sessionType == MediaKeySessionType::PersistentUsageRecord) {
        // 2.1. Let cdm be the CDM instance represented by session's cdm instance value.
        // 2.2. Use cdm to store session's record of key usage, if it exists.
        m_instance->storeRecordOfKeyUsage(m_sessionId);
    }

    // 3. Run the Update Key Statuses algorithm on the session, providing an empty sequence.
    updateKeyStatuses(CDMInstance::KeyStatusVector());

    // 4. Run the Update Expiration algorithm on the session, providing NaN.
    updateExpiration(std::numeric_limits<double>::quiet_NaN());

    // Let's consider the session closed before any promise on the 'closed' attribute is resolved.
    m_closed = true;

    // 5. Let promise be the closed attribute of the session.
    // 6. Resolve promise.
    if (m_closedPromise)
        m_closedPromise.value().resolve(std::nullptr_t());
}

bool MediaKeySession::hasPendingActivity() const
{
    return m_taskQueue.hasPendingTasks() || m_eventQueue.hasPendingEvents();
}

EventTargetInterface MediaKeySession::eventTargetInterface() const
{
	return MediaKeySessionEventTargetInterfaceType;
}

const char* MediaKeySession::activeDOMObjectName() const
{
    notImplemented();
    return "MediaKeySession";
}

bool MediaKeySession::canSuspend() const
{
    notImplemented();
    return false;
}

bool MediaKeySession::canSuspendForDocumentSuspension() const
{
    notImplemented();
    return false;
}

void MediaKeySession::stop()
{
	m_taskQueue.close();
	m_eventQueue.close();
}

EventTargetData* MediaKeySession::eventTargetData()
{
    return &m_eventTargetData;
}

EventTargetData* MediaKeySession::ensureEventTargetData()
{
    return &m_eventTargetData;
}

} // namespace WebCore

#endif
