summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibIMAP/Client.h
blob: f6329547d8adf83f4187fc26f3729254ee6989bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
 * Copyright (c) 2021, Kyle Pereira <hey@xylepereira.me>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/Function.h>
#include <LibIMAP/Parser.h>
#include <LibTLS/TLSv12.h>

namespace IMAP {
class Client {
    friend class Parser;

public:
    Client(StringView host, unsigned port, bool start_with_tls);

    Optional<RefPtr<Promise<Empty>>> connect();
    RefPtr<Promise<Optional<Response>>> send_command(Command&&);
    RefPtr<Promise<Optional<Response>>> send_simple_command(CommandType);
    void send_raw(StringView data);
    RefPtr<Promise<Optional<SolidResponse>>> login(StringView username, StringView password);
    RefPtr<Promise<Optional<SolidResponse>>> list(StringView reference_name, StringView mailbox_name);
    RefPtr<Promise<Optional<SolidResponse>>> select(StringView string);
    RefPtr<Promise<Optional<SolidResponse>>> search(Optional<String> charset, Vector<SearchKey>&& search_keys, bool uid);
    RefPtr<Promise<Optional<SolidResponse>>> fetch(FetchCommand request, bool uid);
    RefPtr<Promise<Optional<SolidResponse>>> store(StoreMethod, Sequence, bool silent, Vector<String> const& flags, bool uid);
    RefPtr<Promise<Optional<ContinueRequest>>> idle();
    RefPtr<Promise<Optional<SolidResponse>>> finish_idle();
    RefPtr<Promise<Optional<SolidResponse>>> status(StringView mailbox, Vector<StatusItemType> const& types);

    void close();

    Function<void(ResponseData&&)> unrequested_response_callback;

private:
    StringView m_host;
    unsigned m_port;
    RefPtr<Core::Socket> m_socket;
    RefPtr<TLS::TLSv12> m_tls_socket;

    void on_ready_to_receive();
    void on_tls_ready_to_receive();

    bool m_tls;
    int m_current_command = 1;

    bool connect_tls();
    bool connect_plaintext();

    // Sent but response not received
    Vector<RefPtr<Promise<Optional<Response>>>> m_pending_promises;
    // Not yet sent
    Vector<Command> m_command_queue {};

    RefPtr<Promise<bool>> m_connect_pending {};

    ByteBuffer m_buffer;
    Parser m_parser;

    bool m_expecting_response { false };
    void handle_parsed_response(ParseStatus&& parse_status);
    void send_next_command();
};
}