Blob.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. /*
  2. * Copyright (c) 2022-2023, Kenneth Myhra <kennethmyhra@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/GenericLexer.h>
  7. #include <LibJS/Runtime/ArrayBuffer.h>
  8. #include <LibJS/Runtime/Completion.h>
  9. #include <LibWeb/Bindings/BlobPrototype.h>
  10. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  11. #include <LibWeb/Bindings/Intrinsics.h>
  12. #include <LibWeb/FileAPI/Blob.h>
  13. #include <LibWeb/Infra/Strings.h>
  14. #include <LibWeb/WebIDL/AbstractOperations.h>
  15. namespace Web::FileAPI {
  16. WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::create(JS::Realm& realm, ByteBuffer byte_buffer, String type)
  17. {
  18. return MUST_OR_THROW_OOM(realm.heap().allocate<Blob>(realm, realm, move(byte_buffer), move(type)));
  19. }
  20. // https://w3c.github.io/FileAPI/#convert-line-endings-to-native
  21. ErrorOr<String> convert_line_endings_to_native(StringView string)
  22. {
  23. // 1. Let native line ending be be the code point U+000A LF.
  24. auto native_line_ending = "\n"sv;
  25. // 2. If the underlying platform’s conventions are to represent newlines as a carriage return and line feed sequence, set native line ending to the code point U+000D CR followed by the code point U+000A LF.
  26. // NOTE: this step is a no-op since LibWeb does not compile on Windows, which is the only platform we know of that that uses a carriage return and line feed sequence for line endings.
  27. // 3. Set result to the empty string.
  28. StringBuilder result;
  29. // 4. Let position be a position variable for s, initially pointing at the start of s.
  30. auto lexer = GenericLexer { string };
  31. // 5. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR from s given position.
  32. // 6. Append token to result.
  33. TRY(result.try_append(lexer.consume_until(is_any_of("\n\r"sv))));
  34. // 7. While position is not past the end of s:
  35. while (!lexer.is_eof()) {
  36. // 1. If the code point at position within s equals U+000D CR:
  37. if (lexer.peek() == '\r') {
  38. // 1. Append native line ending to result.
  39. TRY(result.try_append(native_line_ending));
  40. // 2. Advance position by 1.
  41. lexer.ignore(1);
  42. // 3. If position is not past the end of s and the code point at position within s equals U+000A LF advance position by 1.
  43. if (!lexer.is_eof() && lexer.peek() == '\n')
  44. lexer.ignore(1);
  45. }
  46. // 2. Otherwise if the code point at position within s equals U+000A LF, advance position by 1 and append native line ending to result.
  47. else if (lexer.peek() == '\n') {
  48. lexer.ignore(1);
  49. TRY(result.try_append(native_line_ending));
  50. }
  51. // 3. Let token be the result of collecting a sequence of code points that are not equal to U+000A LF or U+000D CR from s given position.
  52. // 4. Append token to result.
  53. TRY(result.try_append(lexer.consume_until(is_any_of("\n\r"sv))));
  54. }
  55. // 5. Return result.
  56. return result.to_string();
  57. }
  58. // https://w3c.github.io/FileAPI/#process-blob-parts
  59. ErrorOr<ByteBuffer> process_blob_parts(Vector<BlobPart> const& blob_parts, Optional<BlobPropertyBag> const& options)
  60. {
  61. // 1. Let bytes be an empty sequence of bytes.
  62. ByteBuffer bytes {};
  63. // 2. For each element in parts:
  64. for (auto const& blob_part : blob_parts) {
  65. TRY(blob_part.visit(
  66. // 1. If element is a USVString, run the following sub-steps:
  67. [&](String const& string) -> ErrorOr<void> {
  68. // 1. Let s be element.
  69. auto s = string;
  70. // 2. If the endings member of options is "native", set s to the result of converting line endings to native of element.
  71. if (options.has_value() && options->endings == Bindings::EndingType::Native)
  72. s = TRY(convert_line_endings_to_native(s));
  73. // NOTE: The AK::String is always UTF-8.
  74. // 3. Append the result of UTF-8 encoding s to bytes.
  75. return bytes.try_append(s.bytes());
  76. },
  77. // 2. If element is a BufferSource, get a copy of the bytes held by the buffer source, and append those bytes to bytes.
  78. [&](JS::Handle<JS::Object> const& buffer_source) -> ErrorOr<void> {
  79. auto data_buffer = TRY(WebIDL::get_buffer_source_copy(*buffer_source.cell()));
  80. return bytes.try_append(data_buffer.bytes());
  81. },
  82. // 3. If element is a Blob, append the bytes it represents to bytes.
  83. [&](JS::Handle<Blob> const& blob) -> ErrorOr<void> {
  84. return bytes.try_append(blob->bytes());
  85. }));
  86. }
  87. // 3. Return bytes.
  88. return bytes;
  89. }
  90. bool is_basic_latin(StringView view)
  91. {
  92. for (auto code_point : view) {
  93. if (code_point < 0x0020 || code_point > 0x007E)
  94. return false;
  95. }
  96. return true;
  97. }
  98. Blob::Blob(JS::Realm& realm)
  99. : PlatformObject(realm)
  100. {
  101. }
  102. Blob::Blob(JS::Realm& realm, ByteBuffer byte_buffer, String type)
  103. : PlatformObject(realm)
  104. , m_byte_buffer(move(byte_buffer))
  105. , m_type(move(type))
  106. {
  107. }
  108. Blob::Blob(JS::Realm& realm, ByteBuffer byte_buffer)
  109. : PlatformObject(realm)
  110. , m_byte_buffer(move(byte_buffer))
  111. {
  112. }
  113. Blob::~Blob() = default;
  114. JS::ThrowCompletionOr<void> Blob::initialize(JS::Realm& realm)
  115. {
  116. MUST_OR_THROW_OOM(Base::initialize(realm));
  117. set_prototype(&Bindings::ensure_web_prototype<Bindings::BlobPrototype>(realm, "Blob"));
  118. return {};
  119. }
  120. // https://w3c.github.io/FileAPI/#ref-for-dom-blob-blob
  121. WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::create(JS::Realm& realm, Optional<Vector<BlobPart>> const& blob_parts, Optional<BlobPropertyBag> const& options)
  122. {
  123. auto& vm = realm.vm();
  124. // 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.
  125. if (!blob_parts.has_value() && !options.has_value())
  126. return MUST_OR_THROW_OOM(realm.heap().allocate<Blob>(realm, realm));
  127. ByteBuffer byte_buffer {};
  128. // 2. Let bytes be the result of processing blob parts given blobParts and options.
  129. if (blob_parts.has_value()) {
  130. byte_buffer = TRY_OR_THROW_OOM(realm.vm(), process_blob_parts(blob_parts.value(), options));
  131. }
  132. auto type = String {};
  133. // 3. If the type member of the options argument is not the empty string, run the following sub-steps:
  134. if (options.has_value() && !options->type.is_empty()) {
  135. // 1. If the type member is provided and is not the empty string, let t be set to the type dictionary member.
  136. // 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.
  137. // NOTE: t is set to empty string at declaration.
  138. if (!options->type.is_empty()) {
  139. if (is_basic_latin(options->type))
  140. type = options->type;
  141. }
  142. // 2. Convert every character in t to ASCII lowercase.
  143. if (!type.is_empty())
  144. type = TRY_OR_THROW_OOM(vm, Infra::to_ascii_lowercase(type));
  145. }
  146. // 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.
  147. return MUST_OR_THROW_OOM(realm.heap().allocate<Blob>(realm, realm, move(byte_buffer), move(type)));
  148. }
  149. WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::construct_impl(JS::Realm& realm, Optional<Vector<BlobPart>> const& blob_parts, Optional<BlobPropertyBag> const& options)
  150. {
  151. return Blob::create(realm, blob_parts, options);
  152. }
  153. // https://w3c.github.io/FileAPI/#dfn-slice
  154. WebIDL::ExceptionOr<JS::NonnullGCPtr<Blob>> Blob::slice(Optional<i64> start, Optional<i64> end, Optional<String> const& content_type)
  155. {
  156. auto& vm = realm().vm();
  157. // 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.
  158. // User agents must process slice() with start normalized according to the following:
  159. i64 relative_start;
  160. if (!start.has_value()) {
  161. // a. If the optional start parameter is not used as a parameter when making this call, let relativeStart be 0.
  162. relative_start = 0;
  163. } else {
  164. auto start_value = start.value();
  165. // b. If start is negative, let relativeStart be max((size + start), 0).
  166. if (start_value < 0) {
  167. relative_start = max((size() + start_value), 0);
  168. }
  169. // c. Else, let relativeStart be min(start, size).
  170. else {
  171. relative_start = min(start_value, size());
  172. }
  173. }
  174. // 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:
  175. i64 relative_end;
  176. if (!end.has_value()) {
  177. // a. If the optional end parameter is not used as a parameter when making this call, let relativeEnd be size.
  178. relative_end = size();
  179. } else {
  180. auto end_value = end.value();
  181. // b. If end is negative, let relativeEnd be max((size + end), 0).
  182. if (end_value < 0) {
  183. relative_end = max((size() + end_value), 0);
  184. }
  185. // c Else, let relativeEnd be min(end, size).
  186. else {
  187. relative_end = min(end_value, size());
  188. }
  189. }
  190. // 3. The optional contentType parameter is used to set the ASCII-encoded string in lower case representing the media type of the Blob.
  191. // User agents must process the slice() with contentType normalized according to the following:
  192. String relative_content_type;
  193. if (!content_type.has_value()) {
  194. // a. If the contentType parameter is not provided, let relativeContentType be set to the empty string.
  195. relative_content_type = String {};
  196. } else {
  197. // b. Else let relativeContentType be set to contentType and run the substeps below:
  198. // 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.
  199. // 2. Convert every character in relativeContentType to ASCII lowercase.
  200. relative_content_type = TRY_OR_THROW_OOM(vm, Infra::to_ascii_lowercase(content_type.value()));
  201. }
  202. // 4. Let span be max((relativeEnd - relativeStart), 0).
  203. auto span = max((relative_end - relative_start), 0);
  204. // 5. Return a new Blob object S with the following characteristics:
  205. // a. S refers to span consecutive bytes from this, beginning with the byte at byte-order position relativeStart.
  206. // b. S.size = span.
  207. // c. S.type = relativeContentType.
  208. auto byte_buffer = TRY_OR_THROW_OOM(vm, m_byte_buffer.slice(relative_start, span));
  209. return MUST_OR_THROW_OOM(heap().allocate<Blob>(realm(), realm(), move(byte_buffer), move(relative_content_type)));
  210. }
  211. // https://w3c.github.io/FileAPI/#dom-blob-text
  212. WebIDL::ExceptionOr<JS::NonnullGCPtr<JS::Promise>> Blob::text()
  213. {
  214. auto& realm = this->realm();
  215. auto& vm = realm.vm();
  216. // FIXME: 1. Let stream be the result of calling get stream on this.
  217. // 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.
  218. // FIXME: We still need to implement ReadableStream for this step to be fully valid.
  219. // 3. Let promise be the result of reading all bytes from stream with reader
  220. auto promise = JS::Promise::create(realm);
  221. auto result = TRY(Bindings::throw_dom_exception_if_needed(vm, [&]() { return JS::PrimitiveString::create(vm, StringView { m_byte_buffer.bytes() }); }));
  222. // 4. Return the result of transforming promise by a fulfillment handler that returns the result of running UTF-8 decode on its first argument.
  223. promise->fulfill(result);
  224. return promise;
  225. }
  226. // https://w3c.github.io/FileAPI/#dom-blob-arraybuffer
  227. JS::Promise* Blob::array_buffer()
  228. {
  229. // FIXME: 1. Let stream be the result of calling get stream on this.
  230. // 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.
  231. // FIXME: We still need to implement ReadableStream for this step to be fully valid.
  232. // 3. Let promise be the result of reading all bytes from stream with reader.
  233. auto promise = JS::Promise::create(realm());
  234. auto buffer_result = JS::ArrayBuffer::create(realm(), m_byte_buffer.size());
  235. if (buffer_result.is_error()) {
  236. promise->reject(buffer_result.release_error().value().release_value());
  237. return promise;
  238. }
  239. auto buffer = buffer_result.release_value();
  240. buffer->buffer().overwrite(0, m_byte_buffer.data(), m_byte_buffer.size());
  241. // 4. Return the result of transforming promise by a fulfillment handler that returns a new ArrayBuffer whose contents are its first argument.
  242. promise->fulfill(buffer);
  243. return promise;
  244. }
  245. }