FileReader.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. /*
  2. * Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Assertions.h>
  7. #include <AK/Base64.h>
  8. #include <AK/ByteBuffer.h>
  9. #include <LibJS/Heap/Heap.h>
  10. #include <LibJS/Runtime/Promise.h>
  11. #include <LibJS/Runtime/Realm.h>
  12. #include <LibJS/Runtime/TypedArray.h>
  13. #include <LibTextCodec/Decoder.h>
  14. #include <LibWeb/Bindings/Intrinsics.h>
  15. #include <LibWeb/DOM/Event.h>
  16. #include <LibWeb/DOM/EventTarget.h>
  17. #include <LibWeb/FileAPI/Blob.h>
  18. #include <LibWeb/FileAPI/FileReader.h>
  19. #include <LibWeb/HTML/EventLoop/EventLoop.h>
  20. #include <LibWeb/HTML/EventNames.h>
  21. #include <LibWeb/HTML/Scripting/TemporaryExecutionContext.h>
  22. #include <LibWeb/MimeSniff/MimeType.h>
  23. #include <LibWeb/Platform/EventLoopPlugin.h>
  24. #include <LibWeb/Streams/AbstractOperations.h>
  25. #include <LibWeb/Streams/ReadableStream.h>
  26. #include <LibWeb/Streams/ReadableStreamDefaultReader.h>
  27. #include <LibWeb/WebIDL/DOMException.h>
  28. #include <LibWeb/WebIDL/ExceptionOr.h>
  29. namespace Web::FileAPI {
  30. JS_DEFINE_ALLOCATOR(FileReader);
  31. FileReader::~FileReader() = default;
  32. FileReader::FileReader(JS::Realm& realm)
  33. : DOM::EventTarget(realm)
  34. {
  35. }
  36. void FileReader::initialize(JS::Realm& realm)
  37. {
  38. Base::initialize(realm);
  39. WEB_SET_PROTOTYPE_FOR_INTERFACE(FileReader);
  40. }
  41. void FileReader::visit_edges(JS::Cell::Visitor& visitor)
  42. {
  43. Base::visit_edges(visitor);
  44. visitor.visit(m_error);
  45. }
  46. JS::NonnullGCPtr<FileReader> FileReader::create(JS::Realm& realm)
  47. {
  48. return realm.heap().allocate<FileReader>(realm, realm);
  49. }
  50. JS::NonnullGCPtr<FileReader> FileReader::construct_impl(JS::Realm& realm)
  51. {
  52. return FileReader::create(realm);
  53. }
  54. // https://w3c.github.io/FileAPI/#blob-package-data
  55. WebIDL::ExceptionOr<FileReader::Result> FileReader::blob_package_data(JS::Realm& realm, ByteBuffer bytes, Type type, Optional<String> const& mime_type, Optional<String> const& encoding_name)
  56. {
  57. // A Blob has an associated package data algorithm, given bytes, a type, a optional mimeType, and a optional encodingName, which switches on type and runs the associated steps:
  58. switch (type) {
  59. case Type::DataURL:
  60. // Return bytes as a DataURL [RFC2397] subject to the considerations below:
  61. // Use mimeType as part of the Data URL if it is available in keeping with the Data URL specification [RFC2397].
  62. // If mimeType is not available return a Data URL without a media-type. [RFC2397].
  63. return MUST(URL::create_with_data(mime_type.value_or(String {}), MUST(encode_base64(bytes)), true).to_string());
  64. case Type::Text: {
  65. // 1. Let encoding be failure.
  66. Optional<StringView> encoding;
  67. // 2. If the encodingName is present, set encoding to the result of getting an encoding from encodingName.
  68. if (encoding_name.has_value())
  69. encoding = TextCodec::get_standardized_encoding(encoding_name.value());
  70. // 3. If encoding is failure, and mimeType is present:
  71. if (!encoding.has_value() && mime_type.has_value()) {
  72. // 1. Let type be the result of parse a MIME type given mimeType.
  73. auto maybe_type = MimeSniff::MimeType::parse(mime_type.value());
  74. // 2. If type is not failure, set encoding to the result of getting an encoding from type’s parameters["charset"].
  75. if (!maybe_type.is_error() && maybe_type.value().has_value()) {
  76. auto type = maybe_type.release_value().value();
  77. auto it = type.parameters().find("charset"sv);
  78. if (it != type.parameters().end())
  79. encoding = TextCodec::get_standardized_encoding(it->value);
  80. }
  81. }
  82. // 4. If encoding is failure, then set encoding to UTF-8.
  83. // 5. Decode bytes using fallback encoding encoding, and return the result.
  84. auto decoder = TextCodec::decoder_for(encoding.value_or("UTF-8"sv));
  85. VERIFY(decoder.has_value());
  86. return TRY_OR_THROW_OOM(realm.vm(), convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(decoder.value(), bytes));
  87. }
  88. case Type::ArrayBuffer:
  89. // Return a new ArrayBuffer whose contents are bytes.
  90. return JS::ArrayBuffer::create(realm, move(bytes));
  91. case Type::BinaryString:
  92. // FIXME: Return bytes as a binary string, in which every byte is represented by a code unit of equal value [0..255].
  93. return WebIDL::NotSupportedError::create(realm, "BinaryString not supported yet"_fly_string);
  94. }
  95. VERIFY_NOT_REACHED();
  96. }
  97. // https://w3c.github.io/FileAPI/#readOperation
  98. WebIDL::ExceptionOr<void> FileReader::read_operation(Blob& blob, Type type, Optional<String> const& encoding_name)
  99. {
  100. auto& realm = this->realm();
  101. auto const blobs_type = blob.type();
  102. // 1. If fr’s state is "loading", throw an InvalidStateError DOMException.
  103. if (m_state == State::Loading)
  104. return WebIDL::InvalidStateError::create(realm, "Read already in progress"_fly_string);
  105. // 2. Set fr’s state to "loading".
  106. m_state = State::Loading;
  107. // 3. Set fr’s result to null.
  108. m_result = {};
  109. // 4. Set fr’s error to null.
  110. m_error = {};
  111. // 5. Let stream be the result of calling get stream on blob.
  112. auto stream = TRY(blob.get_stream());
  113. // 6. Let reader be the result of getting a reader from stream.
  114. auto reader = TRY(acquire_readable_stream_default_reader(*stream));
  115. // 7. Let bytes be an empty byte sequence.
  116. ByteBuffer bytes;
  117. // 8. Let chunkPromise be the result of reading a chunk from stream with reader.
  118. auto chunk_promise = TRY(reader->read());
  119. // 9. Let isFirstChunk be true.
  120. bool is_first_chunk = true;
  121. // 10. In parallel, while true:
  122. Platform::EventLoopPlugin::the().deferred_invoke([this, chunk_promise, reader, bytes, is_first_chunk, &realm, type, encoding_name, blobs_type]() mutable {
  123. HTML::TemporaryExecutionContext execution_context { Bindings::host_defined_environment_settings_object(realm) };
  124. while (true) {
  125. auto& vm = realm.vm();
  126. // 1. Wait for chunkPromise to be fulfilled or rejected.
  127. Platform::EventLoopPlugin::the().spin_until([&]() {
  128. return chunk_promise->state() == JS::Promise::State::Fulfilled || chunk_promise->state() == JS::Promise::State::Rejected;
  129. });
  130. // 2. If chunkPromise is fulfilled, and isFirstChunk is true, queue a task to fire a progress event called loadstart at fr.
  131. // NOTE: ISSUE 2 We might change loadstart to be dispatched synchronously, to align with XMLHttpRequest behavior. [Issue #119]
  132. if (chunk_promise->state() == JS::Promise::State::Fulfilled && is_first_chunk) {
  133. HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [this, &realm]() {
  134. dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadstart));
  135. }));
  136. }
  137. // 3. Set isFirstChunk to false.
  138. is_first_chunk = false;
  139. VERIFY(chunk_promise->result().is_object());
  140. auto& result = chunk_promise->result().as_object();
  141. auto value = MUST(result.get(vm.names.value));
  142. auto done = MUST(result.get(vm.names.done));
  143. // 4. If chunkPromise is fulfilled with an object whose done property is false and whose value property is a Uint8Array object, run these steps:
  144. if (chunk_promise->state() == JS::Promise::State::Fulfilled && !done.as_bool() && is<JS::Uint8Array>(value.as_object())) {
  145. // 1. Let bs be the byte sequence represented by the Uint8Array object.
  146. auto const& byte_sequence = verify_cast<JS::Uint8Array>(value.as_object());
  147. // 2. Append bs to bytes.
  148. bytes.append(byte_sequence.data());
  149. // FIXME: 3. If roughly 50ms have passed since these steps were last invoked, queue a task to fire a progress event called progress at fr.
  150. // 4. Set chunkPromise to the result of reading a chunk from stream with reader.
  151. chunk_promise = MUST(reader->read());
  152. }
  153. // 5. Otherwise, if chunkPromise is fulfilled with an object whose done property is true, queue a task to run the following steps and abort this algorithm:
  154. else if (chunk_promise->state() == JS::Promise::State::Fulfilled && done.as_bool()) {
  155. HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [this, bytes, type, &realm, encoding_name, blobs_type]() {
  156. // 1. Set fr’s state to "done".
  157. m_state = State::Done;
  158. // 2. Let result be the result of package data given bytes, type, blob’s type, and encodingName.
  159. auto result = blob_package_data(realm, bytes, type, blobs_type, encoding_name);
  160. // 3. If package data threw an exception error:
  161. if (result.is_error()) {
  162. // FIXME: 1. Set fr’s error to error.
  163. // 2. Fire a progress event called error at fr.
  164. dispatch_event(DOM::Event::create(realm, HTML::EventNames::error));
  165. }
  166. // 4. Else:
  167. else {
  168. // 1. Set fr’s result to result.
  169. m_result = result.release_value();
  170. // 2. Fire a progress event called load at the fr.
  171. dispatch_event(DOM::Event::create(realm, HTML::EventNames::load));
  172. }
  173. // 5. If fr’s state is not "loading", fire a progress event called loadend at the fr.
  174. if (m_state != State::Loading)
  175. dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadend));
  176. // NOTE: Event handler for the load or error events could have started another load, if that happens the loadend event for this load is not fired.
  177. }));
  178. return;
  179. }
  180. // 6. Otherwise, if chunkPromise is rejected with an error error, queue a task to run the following steps and abort this algorithm:
  181. else if (chunk_promise->state() == JS::Promise::State::Rejected) {
  182. HTML::queue_global_task(HTML::Task::Source::FileReading, realm.global_object(), JS::create_heap_function(heap(), [this, &realm]() {
  183. // 1. Set fr’s state to "done".
  184. m_state = State::Done;
  185. // FIXME: 2. Set fr’s error to error.
  186. // 5. Fire a progress event called error at fr.
  187. dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadend));
  188. // 4. If fr’s state is not "loading", fire a progress event called loadend at fr.
  189. if (m_state != State::Loading)
  190. dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadend));
  191. // 5. Note: Event handler for the error event could have started another load, if that happens the loadend event for this load is not fired.
  192. }));
  193. }
  194. }
  195. });
  196. return {};
  197. }
  198. // https://w3c.github.io/FileAPI/#dfn-readAsDataURL
  199. WebIDL::ExceptionOr<void> FileReader::read_as_data_url(Blob& blob)
  200. {
  201. // The readAsDataURL(blob) method, when invoked, must initiate a read operation for blob with DataURL.
  202. return read_operation(blob, Type::DataURL);
  203. }
  204. // https://w3c.github.io/FileAPI/#dfn-readAsText
  205. WebIDL::ExceptionOr<void> FileReader::read_as_text(Blob& blob, Optional<String> const& encoding)
  206. {
  207. // The readAsText(blob, encoding) method, when invoked, must initiate a read operation for blob with Text and encoding.
  208. return read_operation(blob, Type::Text, encoding);
  209. }
  210. // https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer
  211. WebIDL::ExceptionOr<void> FileReader::read_as_array_buffer(Blob& blob)
  212. {
  213. // The readAsArrayBuffer(blob) method, when invoked, must initiate a read operation for blob with ArrayBuffer.
  214. return read_operation(blob, Type::ArrayBuffer);
  215. }
  216. // https://w3c.github.io/FileAPI/#dfn-readAsBinaryString
  217. WebIDL::ExceptionOr<void> FileReader::read_as_binary_string(Blob& blob)
  218. {
  219. // The readAsBinaryString(blob) method, when invoked, must initiate a read operation for blob with BinaryString.
  220. // NOTE: The use of readAsArrayBuffer() is preferred over readAsBinaryString(), which is provided for backwards compatibility.
  221. return read_operation(blob, Type::BinaryString);
  222. }
  223. // https://w3c.github.io/FileAPI/#dfn-abort
  224. void FileReader::abort()
  225. {
  226. auto& realm = this->realm();
  227. // 1. If this's state is "empty" or if this's state is "done" set this's result to null and terminate this algorithm.
  228. if (m_state == State::Empty || m_state == State::Done) {
  229. m_result = {};
  230. return;
  231. }
  232. // 2. If this's state is "loading" set this's state to "done" and set this's result to null.
  233. if (m_state == State::Loading) {
  234. m_state = State::Done;
  235. m_result = {};
  236. }
  237. // FIXME: 3. If there are any tasks from this on the file reading task source in an affiliated task queue, then remove those tasks from that task queue.
  238. // FIXME: 4. Terminate the algorithm for the read method being processed.
  239. // 5. Fire a progress event called abort at this.
  240. dispatch_event(DOM::Event::create(realm, HTML::EventNames::abort));
  241. // 6. If this's state is not "loading", fire a progress event called loadend at this.
  242. if (m_state != State::Loading)
  243. dispatch_event(DOM::Event::create(realm, HTML::EventNames::loadend));
  244. }
  245. void FileReader::set_onloadstart(WebIDL::CallbackType* value)
  246. {
  247. set_event_handler_attribute(HTML::EventNames::loadstart, value);
  248. }
  249. WebIDL::CallbackType* FileReader::onloadstart()
  250. {
  251. return event_handler_attribute(HTML::EventNames::loadstart);
  252. }
  253. void FileReader::set_onprogress(WebIDL::CallbackType* value)
  254. {
  255. set_event_handler_attribute(HTML::EventNames::progress, value);
  256. }
  257. WebIDL::CallbackType* FileReader::onprogress()
  258. {
  259. return event_handler_attribute(HTML::EventNames::progress);
  260. }
  261. void FileReader::set_onload(WebIDL::CallbackType* value)
  262. {
  263. set_event_handler_attribute(HTML::EventNames::load, value);
  264. }
  265. WebIDL::CallbackType* FileReader::onload()
  266. {
  267. return event_handler_attribute(HTML::EventNames::load);
  268. }
  269. void FileReader::set_onabort(WebIDL::CallbackType* value)
  270. {
  271. set_event_handler_attribute(HTML::EventNames::abort, value);
  272. }
  273. WebIDL::CallbackType* FileReader::onabort()
  274. {
  275. return event_handler_attribute(HTML::EventNames::abort);
  276. }
  277. void FileReader::set_onerror(WebIDL::CallbackType* value)
  278. {
  279. set_event_handler_attribute(HTML::EventNames::error, value);
  280. }
  281. WebIDL::CallbackType* FileReader::onerror()
  282. {
  283. return event_handler_attribute(HTML::EventNames::error);
  284. }
  285. void FileReader::set_onloadend(WebIDL::CallbackType* value)
  286. {
  287. set_event_handler_attribute(HTML::EventNames::loadend, value);
  288. }
  289. WebIDL::CallbackType* FileReader::onloadend()
  290. {
  291. return event_handler_attribute(HTML::EventNames::loadend);
  292. }
  293. }