Blob.cpp 12 KB

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