FileReader.cpp 15 KB

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