#include "config.h"
#include "JSFile.h"
#include "JSDOMBinding.h"
#include "JSDictionary.h"
#include "WebKitBlobBuilder.h"
#include <runtime/Error.h>
#include <runtime/JSArray.h>
#include <runtime/JSArrayBuffer.h>
#include <runtime/JSArrayBufferView.h>
#include <wtf/Assertions.h>
#include <wtf/CurrentTime.h>
using namespace JSC;
namespace WebCore {
EncodedJSValue JSC_HOST_CALL constructJSFile(ExecState& exec)
{
auto* constructor = jsCast<DOMConstructorObject*>(exec.callee());
ScriptExecutionContext* context = constructor->scriptExecutionContext();
if (!context)
return throwVMError(&exec, createReferenceError(&exec, "File constructor associated document is unavailable"));
JSValue arg = exec.argument(0);
if (arg.isUndefinedOrNull())
return throwVMTypeError(&exec, ASCIILiteral("First argument to File constructor must be a valid sequence, was undefined or null"));
unsigned blobPartsLength = 0;
JSObject* blobParts = toJSSequence(exec, arg, blobPartsLength);
if (exec.hadException())
return JSValue::encode(jsUndefined());
ASSERT(blobParts);
arg = exec.argument(1);
if (arg.isUndefined())
return throwVMTypeError(&exec, ASCIILiteral("Second argument to File constructor must be a valid string, was undefined"));
String filename = arg.toWTFString(&exec).replace('/', ':');
if (exec.hadException())
return JSValue::encode(jsUndefined());
String normalizedType;
Optional<int64_t> lastModified;
arg = exec.argument(2);
if (!arg.isUndefinedOrNull()) {
JSObject* filePropertyBagObject = arg.getObject();
if (!filePropertyBagObject)
return throwVMTypeError(&exec, ASCIILiteral("Third argument of the constructor is not of type Object"));
JSDictionary dictionary(&exec, filePropertyBagObject);
String type;
dictionary.get("type", type);
if (exec.hadException())
return JSValue::encode(jsUndefined());
normalizedType = Blob::normalizedContentType(type);
if (type.isEmpty() || !normalizedType.isEmpty()) {
dictionary.get("lastModified", lastModified);
if (exec.hadException())
return JSValue::encode(jsUndefined());
}
}
if (!lastModified)
lastModified = currentTimeMS();
BlobBuilder blobBuilder;
for (unsigned i = 0; i < blobPartsLength; ++i) {
JSValue item = blobParts->get(&exec, i);
if (exec.hadException())
return JSValue::encode(jsUndefined());
if (ArrayBuffer* arrayBuffer = toArrayBuffer(item))
blobBuilder.append(arrayBuffer);
else if (RefPtr<ArrayBufferView> arrayBufferView = toArrayBufferView(item))
blobBuilder.append(WTFMove(arrayBufferView));
else if (Blob* blob = JSBlob::toWrapped(item))
blobBuilder.append(blob);
else {
String string = item.toWTFString(&exec);
if (exec.hadException())
return JSValue::encode(jsUndefined());
blobBuilder.append(string, ASCIILiteral("transparent"));
}
}
auto file = File::create(blobBuilder.finalize(), filename, normalizedType, lastModified.value());
return JSValue::encode(CREATE_DOM_WRAPPER(constructor->globalObject(), File, WTFMove(file)));
}
}