BlobURLStore.cpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2023, Tim Flynn <trflynn89@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/StringBuilder.h>
  7. #include <AK/URL.h>
  8. #include <LibWeb/Crypto/Crypto.h>
  9. #include <LibWeb/FileAPI/Blob.h>
  10. #include <LibWeb/FileAPI/BlobURLStore.h>
  11. #include <LibWeb/HTML/Origin.h>
  12. #include <LibWeb/HTML/Scripting/Environments.h>
  13. namespace Web::FileAPI {
  14. BlobURLStore& blob_url_store()
  15. {
  16. static HashMap<String, BlobURLEntry> store;
  17. return store;
  18. }
  19. // https://w3c.github.io/FileAPI/#unicodeBlobURL
  20. ErrorOr<String> generate_new_blob_url()
  21. {
  22. // 1. Let result be the empty string.
  23. StringBuilder result;
  24. // 2. Append the string "blob:" to result.
  25. TRY(result.try_append("blob:"sv));
  26. // 3. Let settings be the current settings object
  27. auto& settings = HTML::current_settings_object();
  28. // 4. Let origin be settings’s origin.
  29. auto origin = settings.origin();
  30. // 5. Let serialized be the ASCII serialization of origin.
  31. auto serialized = origin.serialize();
  32. // 6. If serialized is "null", set it to an implementation-defined value.
  33. if (serialized == "null"sv)
  34. serialized = "ladybird"sv;
  35. // 7. Append serialized to result.
  36. TRY(result.try_append(serialized));
  37. // 8. Append U+0024 SOLIDUS (/) to result.
  38. TRY(result.try_append('/'));
  39. // 9. Generate a UUID [RFC4122] as a string and append it to result.
  40. auto uuid = TRY(Crypto::generate_random_uuid());
  41. TRY(result.try_append(uuid));
  42. // 10. Return result.
  43. return result.to_string();
  44. }
  45. // https://w3c.github.io/FileAPI/#add-an-entry
  46. ErrorOr<String> add_entry_to_blob_url_store(JS::NonnullGCPtr<Blob> object)
  47. {
  48. // 1. Let store be the user agent’s blob URL store.
  49. auto& store = blob_url_store();
  50. // 2. Let url be the result of generating a new blob URL.
  51. auto url = TRY(generate_new_blob_url());
  52. // 3. Let entry be a new blob URL entry consisting of object and the current settings object.
  53. BlobURLEntry entry { object, HTML::current_settings_object() };
  54. // 4. Set store[url] to entry.
  55. TRY(store.try_set(url, move(entry)));
  56. // 5. Return url.
  57. return url;
  58. }
  59. // https://w3c.github.io/FileAPI/#removeTheEntry
  60. ErrorOr<void> remove_entry_from_blob_url_store(StringView url)
  61. {
  62. // 1. Let store be the user agent’s blob URL store;
  63. auto& store = blob_url_store();
  64. // 2. Let url string be the result of serializing url.
  65. auto url_string = TRY(URL { url }.to_string());
  66. // 3. Remove store[url string].
  67. store.remove(url_string);
  68. return {};
  69. }
  70. }