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