FileReader.cpp 15 KB

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