Blob.cpp 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. /*
  2. * Copyright (c) 2022, Kenneth Myhra <kennethmyhra@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StdLibExtras.h>
  7. #include <LibJS/Runtime/ArrayBuffer.h>
  8. #include <LibWeb/Bindings/DOMExceptionWrapper.h>
  9. #include <LibWeb/Bindings/IDLAbstractOperations.h>
  10. #include <LibWeb/FileAPI/Blob.h>
  11. namespace Web::FileAPI {
  12. Blob::Blob(ByteBuffer byte_buffer, String type)
  13. : m_byte_buffer(move(byte_buffer))
  14. , m_type(move(type))
  15. {
  16. }
  17. // https://w3c.github.io/FileAPI/#ref-for-dom-blob-blob
  18. DOM::ExceptionOr<NonnullRefPtr<Blob>> Blob::create(Optional<Vector<BlobPart>> const& blob_parts, Optional<BlobPropertyBag> const& options)
  19. {
  20. // 1. If invoked with zero parameters, return a new Blob object consisting of 0 bytes, with size set to 0, and with type set to the empty string.
  21. if (!blob_parts.has_value() && !options.has_value())
  22. return adopt_ref(*new Blob());
  23. ByteBuffer byte_buffer {};
  24. // 2. Let bytes be the result of processing blob parts given blobParts and options.
  25. if (blob_parts.has_value()) {
  26. byte_buffer = TRY(process_blob_parts(blob_parts.value()));
  27. }
  28. String type = String::empty();
  29. // 3. If the type member of the options argument is not the empty string, run the following sub-steps:
  30. if (options.has_value() && !options->type.is_empty()) {
  31. // FIXME: 1. Let t be the type dictionary member. If t contains any characters outside the range U+0020 to U+007E, then set t to the empty string and return from these substeps.
  32. // 2. Convert every character in t to ASCII lowercase.
  33. type = options->type.to_lowercase();
  34. }
  35. // 4. Return a Blob object referring to bytes as its associated byte sequence, with its size set to the length of bytes, and its type set to the value of t from the substeps above.
  36. return adopt_ref(*new Blob(move(byte_buffer), move(type)));
  37. }
  38. DOM::ExceptionOr<NonnullRefPtr<Blob>> Blob::create_with_global_object(Bindings::WindowObject&, Optional<Vector<BlobPart>> const& blob_parts, Optional<BlobPropertyBag> const& options)
  39. {
  40. return Blob::create(blob_parts, options);
  41. }
  42. // https://w3c.github.io/FileAPI/#process-blob-parts
  43. DOM::ExceptionOr<ByteBuffer> Blob::process_blob_parts(Vector<BlobPart> const& blob_parts)
  44. {
  45. // 1. Let bytes be an empty sequence of bytes.
  46. ByteBuffer bytes {};
  47. // 2. For each element in parts:
  48. for (auto const& blob_part : blob_parts) {
  49. auto error = blob_part.visit(
  50. // 1. If element is a USVString, run the following sub-steps:
  51. [&](String const& string) -> ErrorOr<void> {
  52. // NOTE: This step is handled by the lambda expression.
  53. // 1. Let s be element.
  54. // FIXME: 2. If the endings member of options is "native", set s to the result of converting line endings to native of element.
  55. // NOTE: The AK::String is always UTF-8.
  56. // 3. Append the result of UTF-8 encoding s to bytes.
  57. return bytes.try_append(string.to_byte_buffer());
  58. },
  59. // 2. If element is a BufferSource, get a copy of the bytes held by the buffer source, and append those bytes to bytes.
  60. [&](JS::Handle<JS::Object> const& buffer_source) -> ErrorOr<void> {
  61. auto data_buffer = Bindings::IDL::get_buffer_source_copy(*buffer_source.cell());
  62. if (data_buffer.has_value())
  63. return bytes.try_append(data_buffer->bytes());
  64. return {};
  65. },
  66. // 3. If element is a Blob, append the bytes it represents to bytes.
  67. [&](NonnullRefPtr<Blob> const& blob) -> ErrorOr<void> {
  68. return bytes.try_append(blob->m_byte_buffer.bytes());
  69. });
  70. if (error.is_error())
  71. return DOM::UnknownError::create("Out of memory. Failed to process blob parts."sv);
  72. }
  73. return bytes;
  74. }
  75. // https://w3c.github.io/FileAPI/#dfn-slice
  76. DOM::ExceptionOr<NonnullRefPtr<Blob>> Blob::slice(Optional<i64> start, Optional<i64> end, Optional<String> const& content_type)
  77. {
  78. // 1. The optional start parameter is a value for the start point of a slice() call, and must be treated as a byte-order position, with the zeroth position representing the first byte.
  79. // User agents must process slice() with start normalized according to the following:
  80. i64 relative_start;
  81. if (!start.has_value()) {
  82. // a. If the optional start parameter is not used as a parameter when making this call, let relativeStart be 0.
  83. relative_start = 0;
  84. } else {
  85. auto start_value = start.value();
  86. // b. If start is negative, let relativeStart be max((size + start), 0).
  87. if (start_value < 0) {
  88. relative_start = max((size() + start_value), 0);
  89. }
  90. // c. Else, let relativeStart be min(start, size).
  91. else {
  92. relative_start = min(start_value, size());
  93. }
  94. }
  95. // 2. The optional end parameter is a value for the end point of a slice() call. User agents must process slice() with end normalized according to the following:
  96. i64 relative_end;
  97. if (!end.has_value()) {
  98. // a. If the optional end parameter is not used as a parameter when making this call, let relativeEnd be size.
  99. relative_end = size();
  100. } else {
  101. auto end_value = end.value();
  102. // b. If end is negative, let relativeEnd be max((size + end), 0).
  103. if (end_value < 0) {
  104. relative_end = max((size() + end_value), 0);
  105. }
  106. // c Else, let relativeEnd be min(end, size).
  107. else {
  108. relative_end = min(end_value, size());
  109. }
  110. }
  111. // 3. The optional contentType parameter is used to set the ASCII-encoded string in lower case representing the media type of the Blob.
  112. // User agents must process the slice() with contentType normalized according to the following:
  113. String relative_content_type;
  114. if (!content_type.has_value()) {
  115. // a. If the contentType parameter is not provided, let relativeContentType be set to the empty string.
  116. relative_content_type = "";
  117. } else {
  118. // b. Else let relativeContentType be set to contentType and run the substeps below:
  119. // FIXME: 1. If relativeContentType contains any characters outside the range of U+0020 to U+007E, then set relativeContentType to the empty string and return from these substeps.
  120. // 2. Convert every character in relativeContentType to ASCII lowercase.
  121. relative_content_type = content_type->to_lowercase();
  122. }
  123. // 4. Let span be max((relativeEnd - relativeStart), 0).
  124. auto span = max((relative_end - relative_start), 0);
  125. // 5. Return a new Blob object S with the following characteristics:
  126. // a. S refers to span consecutive bytes from this, beginning with the byte at byte-order position relativeStart.
  127. // b. S.size = span.
  128. // c. S.type = relativeContentType.
  129. auto byte_buffer_or_error = m_byte_buffer.slice(relative_start, span);
  130. if (byte_buffer_or_error.is_error())
  131. return DOM::UnknownError::create("Out of memory."sv);
  132. return adopt_ref(*new Blob(byte_buffer_or_error.release_value(), move(relative_content_type)));
  133. }
  134. // https://w3c.github.io/FileAPI/#dom-blob-text
  135. JS::Promise* Blob::text()
  136. {
  137. auto& global_object = wrapper()->global_object();
  138. // FIXME: 1. Let stream be the result of calling get stream on this.
  139. // FIXME: 2. Let reader be the result of getting a reader from stream. If that threw an exception, return a new promise rejected with that exception.
  140. // FIXME: We still need to implement ReadableStream for this step to be fully valid.
  141. // 3. Let promise be the result of reading all bytes from stream with reader
  142. auto* promise = JS::Promise::create(global_object);
  143. auto* result = JS::js_string(global_object.heap(), String { m_byte_buffer.bytes() });
  144. // 4. Return the result of transforming promise by a fulfillment handler that returns the result of running UTF-8 decode on its first argument.
  145. promise->fulfill(result);
  146. return promise;
  147. }
  148. // https://w3c.github.io/FileAPI/#dom-blob-arraybuffer
  149. JS::Promise* Blob::array_buffer()
  150. {
  151. auto& global_object = wrapper()->global_object();
  152. // FIXME: 1. Let stream be the result of calling get stream on this.
  153. // FIXME: 2. Let reader be the result of getting a reader from stream. If that threw an exception, return a new promise rejected with that exception.
  154. // FIXME: We still need to implement ReadableStream for this step to be fully valid.
  155. // 3. Let promise be the result of reading all bytes from stream with reader.
  156. auto* promise = JS::Promise::create(global_object);
  157. auto buffer_result = JS::ArrayBuffer::create(global_object, m_byte_buffer.size());
  158. if (buffer_result.is_error()) {
  159. promise->reject(buffer_result.release_error().value().release_value());
  160. return promise;
  161. }
  162. auto* buffer = buffer_result.release_value();
  163. buffer->buffer().overwrite(0, m_byte_buffer.data(), m_byte_buffer.size());
  164. // 4. Return the result of transforming promise by a fulfillment handler that returns a new ArrayBuffer whose contents are its first argument.
  165. promise->fulfill(buffer);
  166. return promise;
  167. }
  168. JS::Object* Blob::create_wrapper(JS::GlobalObject& global_object)
  169. {
  170. return wrap(global_object, *this);
  171. }
  172. }