Blob.cpp 12 KB

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