LoadRequest.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/ByteBuffer.h>
  8. #include <AK/HashMap.h>
  9. #include <AK/Time.h>
  10. #include <AK/URL.h>
  11. #include <LibCore/ElapsedTimer.h>
  12. #include <LibWeb/Forward.h>
  13. #include <LibWeb/Page/Page.h>
  14. namespace Web {
  15. class LoadRequest {
  16. public:
  17. LoadRequest()
  18. {
  19. }
  20. static LoadRequest create_for_url_on_page(const AK::URL& url, Page* page);
  21. bool is_valid() const { return m_url.is_valid(); }
  22. const AK::URL& url() const { return m_url; }
  23. void set_url(const AK::URL& url) { m_url = url; }
  24. String const& method() const { return m_method; }
  25. void set_method(String const& method) { m_method = method; }
  26. ByteBuffer const& body() const { return m_body; }
  27. void set_body(ByteBuffer const& body) { m_body = body; }
  28. void start_timer() { m_load_timer.start(); };
  29. Time load_time() const { return m_load_timer.elapsed_time(); }
  30. Optional<Page&>& page() { return m_page; };
  31. void set_page(Page& page) { m_page = page; }
  32. unsigned hash() const
  33. {
  34. auto body_hash = string_hash((char const*)m_body.data(), m_body.size());
  35. auto body_and_headers_hash = pair_int_hash(body_hash, m_headers.hash());
  36. auto url_and_method_hash = pair_int_hash(m_url.to_string().hash(), m_method.hash());
  37. return pair_int_hash(body_and_headers_hash, url_and_method_hash);
  38. }
  39. bool operator==(LoadRequest const& other) const
  40. {
  41. if (m_headers.size() != other.m_headers.size())
  42. return false;
  43. for (auto& it : m_headers) {
  44. auto jt = other.m_headers.find(it.key);
  45. if (jt == other.m_headers.end())
  46. return false;
  47. if (it.value != jt->value)
  48. return false;
  49. }
  50. return m_url == other.m_url && m_method == other.m_method && m_body == other.m_body;
  51. }
  52. void set_header(String const& name, String const& value) { m_headers.set(name, value); }
  53. String header(String const& name) const { return m_headers.get(name).value_or({}); }
  54. HashMap<String, String> const& headers() const { return m_headers; }
  55. private:
  56. AK::URL m_url;
  57. String m_method { "GET" };
  58. HashMap<String, String> m_headers;
  59. ByteBuffer m_body;
  60. Core::ElapsedTimer m_load_timer;
  61. Optional<Page&> m_page;
  62. };
  63. }
  64. namespace AK {
  65. template<>
  66. struct Traits<Web::LoadRequest> : public GenericTraits<Web::LoadRequest> {
  67. static unsigned hash(Web::LoadRequest const& request) { return request.hash(); }
  68. };
  69. }